subramanian said:
unsigned char x = 0;
What is the behaviour of ~x according to the C standard.
Strictly speaking it is undefined on the virtual C machine.
After reading K & R, I thought the variable will be promoted to signed
int.
An unsigned char will be promoted to int if an int can hold all the
values
of unsigned char, otherwise it will be promoted to unsigned int. On
hosted implementations, it will promote to int.
Taking bitwise complement should give INT_MAX.
No, taking the bitwise complement of all bits zero yields all bits one.
There
are three different possible representations for signed integers,[1]
two's
complement, ones' complement and sign-magnitude. The value yielded is
different for each form of representation. Indeed, the 'value' may be a
trap
representation on a ones' complement machine.
[1] Unlike C99, C90 does not specify those representations explicitly,
though Committee members have commented that documents from the
'Normative References' component of C90 imply that those 3 options
are the only ones available to a C90 implementation.
But it does not happen here. I get UINT_MAX.
You snipped the bit of code you used to get that value. You previously
wrote...
printf("%u\", ~x);
Though what you probably meant to post was...
printf("%u\n", ~x);
That code invokes undefined behaviour because %u expects an unsigned
int and you supply a value of type int that is not representable as an
unsigned int (on a 2c machine.)[2]
Try...
printf("%d\n", ~x);
This will yield -1 on a 2c machine.
All that said, bitwise operations should generally only be performed on
unsigned integer types of rank equal or higher than unsigned int. Why?
To avoid the sorts of issues of undefined behaviour that you've
encountered.
[2] Strictly speaking, passing an int for %u invokes undefined
behaviour
even if int value is non-negative.
Can someone clarify my doubt ?
Read the texts very carefully. When working on character types, and
especially when working on bitwise operators, be very careful about
implicit promotions (e.g. integral promotions, usual arithmetic
promotions,
etc...).