British0zzy wrote:
Richard Heathfield wrote:
>British0zzy said:
>>Is it a defined operation when I do something like this:
char a = 15;
a = a<<9;
Only on systems where char has at least 10 bits.
The value of CHAR_BIT doesn't matter, not directly. The
expression is evaluated this way:
- First, the starting value of `a' is converted from `char'
to `int' (on most systems) or `unsigned int' (on some).
The statement is now equivalent to one of `a = 15 << 9;'
or `a = 15u << 9;'.
- Next, the shift operator is applied. The numerical result
is within the range of both `int' and `unsigned int', so
now we have either `a = 7680;' or `a = 7680u;'.
- Now comes the dodgy part: The result of the shift is
converted from `int' or `unsigned int' to `char'. If
If `char' is unsigned, all is well: the conversion
yields `7680 % (CHAR_MAX+1)', mathematically speaking.
If `char' is signed and if CHAR_MAX >= 7680 (implying
CHAR_BIT >= 14), all is well again and the conversion
yields `(char)7680'. It's the remaining case that makes
trouble: if `char' is signed and CHAR_MAX < 7680, the
conversion takes us into poorly-charted waters, either
yielding an implementation-defined result or raising an
implementation-defined signal.
- Finally (if we get this far), the converted value is
stored in `a'.
So, yes: The value of CHAR_BIT affects the outcome because
it affects the value of CHAR_MAX used in the conversion, but it
does not affect the operation of or validity of the shift. To
illustrate, changing the second line to `int i = a << 9;' yields
a fragment whose behavior is the same on all implementations .
--
Eric Sosman
es*****@ieee-dot-org.invalid