Shifting in C

M

manu

Hi All,

I have executed the below program and got 0x1f as output...

Can anyone explain me why this output is coming instead of zero?

Compiler - gcc

int main()
{
unsigned long x = 65;
unsigned long y = 0x3F;

y = y >> x;

printf("%x\n",y);

return 1;
}
 
N

Nick Keighley

I have executed the below program and got 0x1f as output...

Can anyone explain me why this output is coming instead of zero?

Compiler - gcc

int main()
{
        unsigned long x = 65;
unsigned long y = 0x3F;

        y = y >> x;

note C has a short version of this

y >>= x;

(someone else answered your actual question)
 
M

manu

Because the result of the shift operator is undefined when the value of
the right operand is greater than or equal to the width in bits of the
left operand. You attempt to shift an unsigned long by 65, but this has
a defined meaning only if sizeof(unsigned long)*CHAR_BIT is at least 66,
which appears not to be true for your implementation.

Additionally:





                 ^^
   "%x" is a specifier for an unsigned int, not for an unsigned long.
   "%x" is an error; it should be "%lx".


               ^^^
   The only value with defined meaning for this return when you don't
include <stdlib.h> is 0.  If you #include <stdlib.h> you gain
EXIT_FAILURE and EXIT_SUCCESS, making 3 values with defined meaning, and
none of them is 1.

Thanks Richard,Nick and Martin for valuable information..
 
W

Walter Roberson

manu said:
If y has 65 or fewer bits (which it probably does), shifting 65 places
invokes undefined behaviour. Therefore any result, or none, is admissible
as far as implementation conformance is concerned.

Additional information: at least one common processor family takes the
shift code modulo 32 when shifting 32 bit numbers. That's an
implementation detail and perfect permitted by the standard section
that Richard cited; just thought you might want to know how you
ended up with the particular answer you did.
 
W

Walter Banks

Bet GCC masked x (and or mod) so shift would be <= of bits in y. If y had less than 65 bits then the shift would be 1 ie a result of 0x1f.

w..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,112
Latest member
VinayKumar Nevatia
Top