1
int16_t a = -1;
a >>= 2;

what is the value of a, is the answer -1 or 0 and could you explain why?

does integer division occur and then the floor function used, or does it simply shift all the 1s in 2s compliment to the right thus resulting in a still being -1 or does it truncate division resulting in 0.

asdffgd ff
  • 11
  • 1
  • 2
    why don't you run the code and see? – joel goldstick Jun 21 '15 at 11:09
  • because im taking an on paper exam tmrw at 9 o clock i dont have the development environment on my computer lol – asdffgd ff Jun 21 '15 at 11:10
  • i would also like to know how the result is determined – asdffgd ff Jun 21 '15 at 11:11
  • 1
    Look here: http://stackoverflow.com/questions/1857928/right-shifting-negative-numbers-in-c – joel goldstick Jun 21 '15 at 11:13
  • 4
    The result of right shift for signed integer is implementation-defined. It may be arithmetic or logical shift depending on if sign bit is propagated or not. – Grzegorz Szpetkowski Jun 21 '15 at 11:20
  • 2
    @joelgoldstick: It's a good thing he didn't "run the code and see". Since this is implementation-defined behavior, he would have learned how his compiler implements it, but very definitely not how other compilers implement it. "Run it and see" can be a very dangerous tool! – Steve Summit Jun 21 '15 at 12:10

2 Answers2

4

For C Language Draft 6.5.7 Bitwise shift operators 5 :

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined

That means that it is correct an not undefined behaviour, but each compiler may decide do fill bits with 1 or 0.

The result can then be -1 (filling with 1 bits) or 16383 = 0x3FFF (with 0 bits)

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • 4
    ... or any other value. Implementation-defined means the implementation can define the resulting value however it chooses, as does undefined or unspecified. The distinction between UB and implementation-defined behaviour is that the implementation's manual must document implementation-defined behaviour. – autistic Jun 21 '15 at 12:00
0

When we do a right shift, the sign bit remains unchanged for the signed data type so if a equals -1 i.e. all the bits of the data are 1. If we do right shift no matter by how many bits, the value of the data remains unchanged. So the value of a remains to be -1.This is what happens for most of the compilers.But the answer is dependent on implementation of compiler