What variable "a" do I need to have to make my "shot" variable equal to 0?
This is the code.
int shot = 0;
shot |= 1 << a;
CodePudding user response:
There is no reliable solution to the problem.
Regarding the bit-shift operators, §6.5.7 ¶3 of the ISO C11 standard states the following:
If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
Therefore, you can only solve this problem by invoking undefined behavior and hope that your compiler will give you the result that you want.
CodePudding user response:
There is no value for a
such that shot
becomes 0
in a valid code (no Undefined Behavior). There are other answers here with standard quotes showing why that is. clang can actually prove this and generates code that assumes shot
becomes non zero:
int foo(int a)
{
int shot = 0;
shot |= 1 << a;
return shot == 0;
}
foo(int): # @foo(int)
xor eax, eax
ret
CodePudding user response:
By the standard, no value will work. You can't shift by greater than or equal to the left-hand data type's width, nor by a negative value, so all you can do is move the 1
0 to 31 bits left (assuming int
is 32 bits), which not enough to force it off the end; you'd be bitwise-or-ing something with shot
, which would make it non-zero no matter what.
The behavior would be the same if you used =
instead of |=
; |=
where the left-hand side is 0
is the same as =
, since the union of all set bits, where one side has no bits set, is the same as the bits set on the other side.