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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With