1

I'm writing some code and find this issue. I'm curious about why does this happen.

The code is as follows:

int n = sizeof(int)*8;
int mask_two = (-1<<n);
cout<<"1:"<<hex<<mask_two<<endl;

int y = -1<<(sizeof(int)*8);
cout<<"2:"<<hex<<y<<endl;

When I compile this code, the output is:

1:ffffffff
2:0

Why are the ouput #1 and output #2 not the same value? The compile is Visual C++ 10.0. What is the root cause of this problem?

Jenz
  • 8,280
  • 7
  • 44
  • 77
Roger Zhu
  • 65
  • 1
  • 10

1 Answers1

6

Firstly, left-shifting negative values produces undefined behavior in C++11, although C++03 (and before) did not say that explicitly.

Secondly, you are not allowed to shift any values by their full bit-width or more. This is also undefined behavior. And that is exactly what you are doing: you are shifting an int value by bit-width of type int (assuming that CHAR_BIT is 8 on your platform).

The allowed values of shift counter in your example can range from 0 to sizeof(int) * CHAR_BIT - 1. You are venturing out of that allowed range.

The difference in the results is probably caused by the fact that the first value was calculated at run-time and the second one at compile-time. These calculation algorithms worked differently on your input, which is why the result is different. This is OK, since the behavior is undefined anyway.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765