This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
Re: C/C++ Bug (shifting chars.)
- To: osv at javad dot ru
- Subject: Re: C/C++ Bug (shifting chars.)
- From: Martin von Loewis <martin at mira dot isdn dot cs dot tu-berlin dot de>
- Date: Tue, 21 Jul 1998 22:01:24 +0200
- CC: egcs-bugs at cygnus dot com
- References: <35B46101.D17F90FA@javad.ru>
> 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 bitfield width);
>> otherwise, the value is implementationdefined.
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