Search code examples
c++visual-studio-2012language-lawyerbitundefined-behavior

Why the following two programs yield different outputs? (C++, bit operation, VS 2012)


Program 1:

int x = 4 ^ (4>>32);
cout << x << endl;

Output is 4

Program 2:

int x = 4;
int y = x ^ (x>>32);
cout << y << endl;

Output is 0


Solution

  • Both code-snippets induce undefined behavior if int has 32 bit or less. [expr.shift]/1:

    The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

    Hence an implementation is not in any way obliged to provide consistent results.