Re: The result of 1 << 32
- From: Christian Bau <christian.bau@xxxxxxxxxxxxxxxxxxxx>
- Date: Sun, 30 Oct 2005 11:20:08 +0000
In article <dk1j2q$548$1@xxxxxxxxxxxxxxxxxxxxxxx>,
roberson@xxxxxxxxxxxxxxxxxx (Walter Roberson) wrote:
> In article <slrndm762i.o4v.jmabel@xxxxxxxxxxxxx>,
> Jordan Abel <jmabel@xxxxxxxxxx> wrote:
> >On 2005-10-29, mrby <bianying@xxxxxxxxx> wrote:
>
> >> Why 1<<i and 1<<32 get different result? I had thought
> >> both of them would get 0x0.
>
> >A theory: the 1<<32 is calculated at compile time [and the compiler
> >itself is smart enough to do this] while the 1<<i value is
> >calculated at runtime - now, if your processor's LSH instruction
> >only accepts a 5-bit immediate operand.
>
> >According to the standard, shifting by a number greater than or
> >equal to the field width is undefined.
>
> I don't have my reference material here, but I seem to recall that
> constant calculations are supposed to be done "as if" they were
> done at run-time. Possibly that only applied to calculations in
> preprocessor expressions.
>
> If my recollection is correct, then even though the shift behaviour
> is undefined, would it not be required to be consistant?
"Undefined behavior" includes permission to be inconsistent. If the
hardware produces a random number as a result of trying to calculate 1
<< 32, then the compiler can do the same thing at compile-time.
In many implementations, it would be possible to define the behavior of
x << y for arbitrary values of y. If the implementation defines the
behavior, then it would implement it both at compile time and at runtime
consistently with that definition.
If the hardware behaves consistently, but the implementation doesn't
actually _define_ that behavior, then all bets are off. However, this
could be the source of an incredibly hard to find bug. For example, in x
<< y a compiler might figure out that y always has the same value at a
high enough optimisation level. So in the example
int i = 32;
int result = 1 << i;
a compiler might do a shift at runtime when it is not optimising, and do
a shift at compile time when it is optimising. Good luck finding the bug
if that happens.
.
- References:
- The result of 1 << 32
- From: mrby
- Re: The result of 1 << 32
- From: Jordan Abel
- The result of 1 << 32
- Prev by Date: Re: PLEASE HELP - Fundamental C language question
- Next by Date: Re: A Simple C Code to Discuss
- Previous by thread: Re: The result of 1 << 32
- Next by thread: really need help!!!
- Index(es):
Relevant Pages
|