Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a boolean value based on an integer

I found this statement is some old code and it took me a second to figure out...

IsTestActive = (TestStateID == 1 ? true : false);

Please correct me if I'm wrong but isn't this the same as this one?:

IsTestActive = (TestStateID == 1);

If it is, why would you ever want to use the first? Which one is more readable? (I think the latter, but I'd like to see what others think.)

like image 706
chills42 Avatar asked Jan 07 '09 14:01

chills42


People also ask

What is the integer value for boolean true?

Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.

What is the boolean value of 2?

There are only two boolean values. They are True and False . Capitalization is important, since true and false are not boolean values (remember Python is case sensitive).

Can you assign 0 to boolean?

Boolean Variables and Data Type ( or lack thereof in C )Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Is a bool an integer?

There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers.


2 Answers

Yes, it is exactly the same.

Yes, the latter is more readable.

like image 111
j_random_hacker Avatar answered Oct 01 '22 08:10

j_random_hacker


IsTestActive = (TestStateID == 1);

is definitely more readable.

You could make a case for defining a constant

ACTIVE = 1

then replacing the boolean variable IsTestActive with

(TestStateID == ACTIVE)

The way the code is now, the state of the boolean IsTestActive will be erroneous if the state of TestStateID changes without updating the boolean. Bypassing the boolean and testing the real source of the information you're after will remove the possibility of this error.

like image 36
Bill the Lizard Avatar answered Oct 01 '22 08:10

Bill the Lizard