chasep255
chasep255

Reputation: 12185

Strange bool values

I have this class which has a private bool member variable call positive. I want to check to see if both my class and the number I am adding to it are both positive so I wrote the expression

positive == (n > 0) //n is of type int

But for some reason when both are positive this evaluates to false. I then did a cout on positive and it has a value of 204! I though a boolean only holds 1 or 0. That would be why this is evaluating to false but why is that and how do I fix it? I am using Visual Studio 2013.

Just to clarify it should be == because I want to know if the sign is the same. So I want it to be true if both are negative or both are positive. I think I solved the problem which was that positive in one particular test case wasn't being initialized. But still why would a bool variable even if uninitialized contain a value larger and 1?

Upvotes: 3

Views: 5916

Answers (2)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20759

As per the standard, getting the value of an uninitialized variable is undefined behavior. Since the actual size of a bool can be more than one bit, a bool variable containing rubbish can even hold bad values like 254. Welcome in the C++ hell!

And since (n > 0) evaluates to 1, 254 == 1 is false.

The bug is most likely due to the fact that positive never got a meaningful value since the object that contains it come into existence.

Search for a positive = something into your code and see if it is executed at least once before you use it.


Edited after Konrad comment:

The problem is most likely due to the fact that == is implemented between int-s and not bool-s relying on a bool-to-int promotion assuming the implementation of bool use 0 for false and 1 for true (and since && and || between int-s assume 0 for false and non-zero for true, bool-to-int promotion can be an identity).

This can be seen as a "compiler unfairness", but -since in the space of integer there is one false and bilions of trues- if operator==(bool,bool) was applied, there where more chance the uninitialized bug wold have been not discovered.

Treating bool as int in the arithmetic operations (not logic ones) makes bad-bool values to come out, thus revealing the bug.

Of course, since behind it there is an UB, it's all in an implementation choice. And it is int the freedom of each reading this to think I'm try to sell a bug as a feature.

Upvotes: 4

bobobobo
bobobobo

Reputation: 67306

Oh, you have a == where you should have an =.

The == doesn't assign, it checks for equality

Should be

bool positive = (n > 0) //n is of type int

bool generally holds only 1 or 0 after assignment. The only reason I can imagine you would see 204 in a bool is if the variable was uninitialized (so it had a junk value).

Upvotes: -1

Related Questions