In the following expression, the result of the left shift operation is assigned to the variable i
.
int i;
i = 7 << 32;
printf("i = %d\n",i);
In the following expression, the left shift assignment operation is carried.
int x = 7;
x <<= 32;
printf("x = %d\n",x);
Both the above expressions gave different results. But it's not the same with the following two expressions. Both of them gave the same result. So what could be the reason for the above expressions to return different values?
int a;
a = 1 + 1;
printf("a = %d\n",a);
int b = 1;
b += 1;
printf("b = %d\n",b);
The C standard says:
The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression’s type.
So, it is undefined behavior because int
is normally 32
bits in size, which means that only 0
through 31
steps are well-defined.