Reputation: 370
This expression is one way to evaluate 2^x (I am aware of the dangers of this approach):
2 << (x-1)
Substitute x=0 and the expression gives the desired result of 1. However when it is placed in a function, it always returns 0:
int fast_2_to_the(int x) {
return 2 << (x-1);
}
This can be observed in this program:
int main(int argc, char *argv[]) {
printf("2 << (0-1) = %d\n", 2 << (0-1));
printf("fast_2_to_the(0) = %d\n", fast_2_to_the(0));
return 0;
}
Which gives the following output:
2 << (0-1) = 1
fast_2_to_the(0) = 0
Why is this happening? I'm a beginner to C and have recently been learning about bitwise operators, so any relevant advice would be appreciated.
Upvotes: 2
Views: 77
Reputation: 37904
What you'are experiencing is undefined behavior according to every C Standard, from ancient C89 through C11.
From N1570 (C11 draft) 6.5.7/3
Bitwise shift operators:
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. 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.
Upvotes: 3
Reputation: 126777
A bit shift with negative right operand is undefined behavior as per C99 §6.5.7 ¶3. That means that the compiler is free to emit code that may not work reliably in case you have a negative shift (or, as per the usual rules about undefined behavior, it may as well make demons fly out of your nose).
The correct way to perform that shift is, as suggested in the comments, 1 << x
, which should work fine as long as the result does not exceed the range of int
.
Upvotes: 6