Strange bool values

I have this class that has a private bool variable. I want to check, like my class, and the number I add to it is both positive, so I wrote an expression

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

But for some reason, when both are positive, it evaluates to false. Then I did a positive result, and it matters 204! I, although the logical value has only 1 or 0. That's why it is evaluated as false, but why is it and how to fix it? I am using Visual Studio 2013.

Just for clarification, this should be ==, because I want to know if the sign is the same. Therefore, I want this to be true if they are both negative or both positive. I think that I solved a problem that was positive in one particular case and was not initialized. But still, why does the bool variable, even if uninitialized, contain a value greater than 1?

+2
source share
3 answers

According to the standard, getting the value of an uninitialized variable is undefined behavior. Since the actual bool size can be more than one bit, the bool variable containing garbage can even contain bad values, such as 254. Welcome to hellish C ++!

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

, , , positive , , , .

positive = something , , .


Konrad:

, , , == int-s, bool-s, bool-to-int, , bool 0 false 1 true ( && || int-s 0 true, bool-to-int ).

" ", , operator==(bool,bool), , , .

bool int ( ) , bad-bool , .

, UB, . , , .

+2

, ==, =.

== ==,

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

bool 1 0 . , , 204 bool, - ( ).

0

Use logical operator &&:

positive && (n > 0)

In the end you can try !!positive == (n > 0).

-1
source

Source: https://habr.com/ru/post/1794158/


All Articles