Patrick
Patrick

Reputation: 1966

Integer not comparing equal to its value

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.

Upvotes: 2

Views: 177

Answers (3)

user2512323
user2512323

Reputation:

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.

Upvotes: 5

Andres
Andres

Reputation: 51

As deniss already pointed out, accessing an array out of bounds is undefined behaviour, so maybe that's the cause. Make sure to check for the array's bounds, too.

So if it's OK to count every selection_color of the array, you could try:

const int MAX_FB_VALUES = 6;

// ...

int countOfGreen = 0;

for (int i = 0; i < MAX_FB_VALUES; ++i)
{
    if(ch->fb[i]->selection_color() == FL_GREEN)
        ++countOfGreen;
}

std::cout << countOfGreen << std::endl;
std::cout << std::boolalpha << (countOfGreen == MAX_FB_VALUES) << std::endl;

Although it would be better to use a container anyway, of course.

Upvotes: 1

ScottMcP-MVP
ScottMcP-MVP

Reputation: 10415

The literal '6' is not an integer and does not have a value of 6.

Upvotes: 1

Related Questions