Feng
Feng

Reputation: 87

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

Upvotes: 2

Views: 67

Answers (1)

Columbo
Columbo

Reputation: 60999

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.

Upvotes: 2

Related Questions