Re: Strange bit shifting result with gcc - am I missing something obvious?




"Gordon Burditt" <gordonb.obxrf@xxxxxxxxxxx> wrote in message
news:13v0jkqh24l8r46@xxxxxxxxxxxxxxxxxxxxx
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?

Thanks

B2003

When I compile tyour code with lcc-win I get:

Warning tshift.c: 2 no type specified. Defaulting to int

The prototype for main is:
int main(void)

Warning tshift.c: 5 missing prototype for printf

You did not include <stdio.h>

Warning tshift.c: 5 shift by 32 is undefined

The number of bits shifted is greater than sizeof(int)*CHAR_BIT
This is undefined!

Isn't the above error message misleading (assuming you're running
in a typical 32-bit setup)? The number of bits shifted is *NOT*
greater than sizeof(int)*CHAR_BIT, and the result is still undefined.

The actual warning (not error) is:

Warning tshift.c: 5 shift by 32 is undefined

Which is correct.

I was interested however in investigating why 1<<32 gave 16777216 and found
that slightly odd code. You could argue it doesn't matter, but just blindly
shifting the value by whatever was in a register seemed wrong. And jacob
fixed this although he wasn't asked to (and will doubtless now break some
programs :-).

--
Bart


.



Relevant Pages

  • xemacs installation problems
    ... checking for gcc... ... checking whether we are using GNU C... ... checking size of int... ... configure: warning: No OffiX without generic Drag'n'Drop support ...
    (comp.os.linux.misc)
  • Re: bug in Real-Time Preemption
    ... lib/rwsem.c:153: warning: type defaults to `int' in declaration of `type name' ... send the line "unsubscribe linux-kernel" in ...
    (Linux-Kernel)
  • Re: error
    ... foo.c:50: warning: string constant runs past end of line ... foo.c:7: warning: declaration of `n' shadows global declaration ... foo.c:29: warning: return type of `main' is not `int' ... char check(int n_, ...
    (comp.lang.c)
  • 2.6.13-rt14 build problem on Powerpc board
    ... kernel/ntp.c:84: warning: excess elements in scalar initializer ... kernel/ntp.c:104: warning: type defaults to `int' in declaration of ... send the line "unsubscribe linux-kernel" in ...
    (Linux-Kernel)
  • Re: want to install
    ... gperl.h:60: warning: type defaults to 'int' in declaration of 'gperl_alloc_temp' ... gperl.h:61: warning: type defaults to 'int' in declaration of 'gperl_filename_from_sv' ... gperl.h:80: error: syntax error before 'type' ...
    (perl.beginners)