This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: C/C++ Bug (shifting chars.)


> The following program prints incorrect result "7f ffffffff" 
> (should be "ffffffff ffffffff", I believe).

gcc is right, at least for C++ (should be the same for
C). [expr.shift] says

>> The operands shall be of integral or enumeration type and integral
>> promotions are performed. The type of the result is that of the
>> promoted left operand.

So the result of the shift is 'int'. Therefore, (0x7f << 3 >>3) gives
(int)0x7f, writing it back to a char gives 0x7f. OTOH, (0x7f << 3)
gives 0x3f8, which cannot be represented in a char; therefore, the
value is undefined ([conv.integral]/3):

>> If the destination type is signed, the value is unchanged if it can
>> be represented in the destination type (and bit­field width);
>> otherwise, the value is implementation­defined.

gcc defines char as signed, and this as truncation of MSBs on i386.

If you want to set the three MSBs of a char, use

  c1 = c | (7 << (8*sizeof(char)-3));

Regards,
Martin


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]