Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if boolean is true? [closed]

Tags:

bool foo = true;  // Do this? if (foo) { }  // Or this? if (foo == true) { } 

I like one of them and my coworker the other. The result is the same, but what is (more) correct?

like image 949
Peter Hedberg Avatar asked Sep 10 '10 13:09

Peter Hedberg


People also ask

How do you know if a Boolean variable is true?

To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!

How do you check if a boolean is null?

Boolean testvar = null; if (testvar == null) { ...} Yes, because then hideInNav holds a reference to a Boolean object and can be null (no reference assigned). Therefor you can check if the reference is null .

Is true == true in Java?

Answer: Boolean is a primitive data type that takes either “true” or “false” values. So anything that returns the value “true' or “false” can be considered as a boolean example. Checking some conditions such as “a==b” or “a<b” or “a>b” can be considered as boolean examples. Q #3) Is boolean a keyword in Java?

How do you check if a boolean is true in Python?

Syntax. If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.


1 Answers

Almost everyone I've seen expressing an opinion prefers

if (foo) { } 

Indeed, I've seen many people criticize the explicit comparison, and I may even have done so myself before now. I'd say the "short" style is idiomatic.

EDIT:

Note that this doesn't mean that line of code is always incorrect. Consider:

bool? maybeFoo = GetSomeNullableBooleanValue(); if (maybeFoo == true) {     ... } 

That will compile, but without the "== true" it won't, as there's no implicit conversion from bool? to bool.

like image 130
Jon Skeet Avatar answered Oct 22 '22 22:10

Jon Skeet