|
|
jacob navia <jacob@xxxxxxxxxx> writes:
> Boltar wrote:
>> On 32 bit linux with gcc 4.2 I get unexpected results with this code:
>>
>> main()
>> {
>> int bits = 32;
>> printf("%d\n",(int)1 << (int)32);
>> printf("%d\n",(int)1 << bits);
>> }
>>
>>
>> The first printf gives a result of 0, the second gives 1. I checked
>> with sizeof() and ints are definately 32 bits in size.
>>
>> I'm sure I'm missing something obvious but can someone tell me what?
[...]
> Warning tshift.c: 5 shift by 32 is undefined
>
> The number of bits shifted is greater than sizeof(int)*CHAR_BIT
> This is undefined!
[...]
You mean greater than *or equal to*, right?
See C99 6.5.7p3:
If the value of the right operand is negative or is greater than
or equal to the width of the promoted left operand, the behavior
is undefined.
The underlying reason for this rule is that different hardware behaves
differently when shifting by a number of bits greater than or equal to
the size of the value being shifted. For example, some CPUs might
ignore the high-order bits of the shift count. By leaving the
behavior undefined, the standard allows the native shift instruction
to be used without extra fix-up code even when the value of the right
operand isn't known at compile time.
--
Keith Thompson (The_Other_Keith) <kst-u@xxxxxxx>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
|
|