I've got a piece of code I am trying to debug, which is producing bizarre results. An integer, which very clearly contains the value six, compares false to the literal 6.
In my code, this code:
int allGreen = 0;
int index = 0;
while (ch->fb[index]->selection_color() == FL_GREEN)
{
++allGreen;
++index;
}
std::cout << allGreen << std::endl;
std::cout << std::boolalpha << (allGreen == 6) << std::endl;
Produces the output:
6
false
I am compiling with g++ 4.8.2 on Ubuntu.
How can this possibly happen?
Edit: Removing all green from the condition doesn't help. Edit 2: index and allGreen are equal, as expected. Neither is equal to 6, despite both being 6.
What is the size of ch->fb
array? If it is 6 or less, it could be compiler optimizing undefined behavior here.
When seeing some simple loop like
while ( a[i] ) i++;
Compiler can make an assumption that i
never goes outside of a
array, otherwise program invokes undefined behavior. That is i
lies between 0
and size of a - 1
.
Later, if compiler sees something like i == 8
, there 8
is larger than size of a - 1
, it replaces this condition with false
.
Just to be sure, you can look at assembly code.