xidui xidui -4 years ago 71
C Question

Strange behavior in C when comparing integers

This problem is encountered in my mac environment where the gcc version is shown below:

Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix

The code segment is from one of the function.

int someFunction(int x, int n) {
int TMin_n = -(1 << (n-1));
int TMax_n = (1 << (n-1)) - 1;
int a = -2147483648;
printf("%s\n", x == a ? "true" : "false"); // true
printf("%s\n", x <= TMax_n ? "true" : "false"); // false
printf("%s\n", a <= TMax_n ? "true" : "false"); // true
printf("%d %d %d\n", TMin_n, x, TMax_n); // -2147483648 -2147483648 2147483647
return 0;

a is equal to x, but why they have different behavior when comparing to TMax_n?


all the data types in this code segment is


Thanks everyone. I just tried the same code on an ubuntu machine and that works fine. It only stuck on my MAC.Seems that it is a problem related with the compiler.

Answer Source

I tried your snippet using an online clang compiler and got the results from the question. I am presuming the code (including the function call) gets completely inlined, and then the compiler optimizes away all comparisons it finds constant.

The line in question seems to be:

int TMax_n = (1 << (n-1)) - 1;

If I explicitly cast (1 << (n-1)) to unsigned, the issue goes away:

int TMax_n = (int) ((unsigned)(1 << (n-1)) - 1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download