[vox-tech] C - passing chars and pointer to chars

Jeffrey J. Nonken jjn_lugod at nonken.net
Sun Jun 4 20:32:28 PDT 2006


On Sun, 4 Jun 2006 13:29:08 -0400
p at dirac.org (Peter Jay Salzman) wrote:

> the "value" of i and j is the same "value" as c.  the only provisio
> is how that value is interpreted.  since i and j are both signed
> ints, when you print them with printf() or cout, the pattern will be
> interpreted as an unsigned int, that is, 255.  not -1.
> 
> to summarize, someFunction() doesn't change the value of c.

If the compiler treats native char as unsigned:

i will be 0x000000ff or 255.
j will be 0x000000ff or 255.

If the compiler treats native char as signed:

i will be 0xffffffff or -1.
j will be 0x000000ff or 255.

That's because when it converts -1 from a signed char (8-bit) to a
signed int (16 bit or larger, I'm assuming native 32 bit here, but it
doesn't matter) it does a sign extend. When you pass an unsigned
pointer and cast it as a signed pointer you treat the value in the
variable differently.

Shrug it off if you will, but -1 and 255 are VERY different values.
Treating them as the same can cause some real headaches. Depending on
one native implementation and then porting to another platform that
might have a different implementation can cause some pretty bad
headaches too, because things that worked just fine suddenly break for
no obvious reason. (For example, expecting a native 16-bit integer to
wrap above 0xffff and then porting to an implementation that uses native
32-bit integer. And if that sounds like the voice of experience
talking, well, it is. :)

THAT is why char * and unsigned char * and signed char * are three
entirely different animals and should be treated as such.

And when you DO figure out the reason you spend the next month
sifting through the code trying to find all the instances of native
whatever and trying to determine whether each one needs to be changed
to explicit signed, unsigned, short, long, and so on. That's why I like
to be explicit up front.

And I would not use printf()'s behaviour as the only yardstick for this
issue.


More information about the vox-tech mailing list