I looked for an answer for two days to this with no success. I’ve never come across this problem before so I’ll try my best. Please bear with me.
I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:
file.h
...
short id;
...
file.cc
id = 0;
while (id < some_large_number)
{
id = foo();
if (id == 2)
{
//do something
}
else if (id == 2900)
{
//do something
}
else if (id == 30000)
{
//do something
}
else if (id == 40000)
{
//do something
}
else if (id == 45000)
{
//do something
}
else
{
//do something else
}
}
The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:
As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.
Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don’t understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?
Thanks so much. I hope this is okay for a first question.
short is 16 bits long and its range is -32768 to 32767. So it can never be 40000 or 45000 and compiler eliminated dead code (as it will never be reached).