Does the code below make any non-portable assumptions other than
CHAR_BIT==8?
char buf[100];
/* do things with buf */
if( !(buf[0]^0xFF) ) /* assume CHAR_BIT is 8 - test for equality */
On a sane implementation, I think this line would always be
equivalent to either
if (buf[0] == (char)0xFF)
or
if ((unsigned char)buf[0] == 0xFFu)
Why would you think that?
The operands of the "^" operator are subject to the usual arithmetic
promotions (and constrained to be integers, hence really just the
integer promotions). If plain char is signed, then, and if buf[0]
holds 0xff with CHAR_BIT being 8, buf[0] must be signed and represents
the value -1. Of course, int is at least 16 bits, and a typical
implementation would wind up with the bit pattern 0xffff or 0xffffffff
on the left. The right is just the integer constant 0xff or (int)255,
and the result of the xor is likely to be 0xff00 or 0xffffff00.
But on an unreasonable yet conforming implementation the evaluation
of (buf[0]^0xFF) could trap, invoking undefined behavior. (On such
implementations, 'char' would necessarily be signed and have one trap
representation.)
Yes, this is also possible. I think the fact that it does not
work on most real implementations is more important, though.
In short: I can't think of any use for this construct, and it's
more dangerous than it is helpful, so I would avoid it like the
plague.
Indeed.