"If ([bool] == true)" requires one more step than "if ([bool])"?

This is a purely pedantic question to express your curiosity.

I am inclined to the last option in the question (like this: if (boolCheck) { ... } ), and my colleague always writes the first one ( if (boolCheck == true) { ... } ). I always teased him, and he always explained it as an old habit when he started programming.

But it occurred to me today that actually writing out the entire == true part may require an additional step for processing, since any expression with the == operator is evaluated using a Boolean value. It's true?

In other words, as I understand it, the option without the string == true can be described as follows:

  • Check x

As long as option c , the line == true will be more like:

  • Let Y be true, if X is true, otherwise false
  • Check y

Am I right? Or maybe any normal compiler / interpreter will end this difference? Or am I not noticing something, and in fact there is no difference?

Obviously, there will be no difference in the actual performance observed. As I said, I'm just curious.

EDIT: Thanks to everyone who posted the collected results to illustrate if there were different steps between the two approaches. (It seems that in most cases they were, albeit slightly.)

I just want to repeat that I did not ask what the “right” approach is. I understand that many people prefer each other. I also understand that, logically, they are identical. I was just wondering if the actual operations performed by the processor are exactly the same for both methods; as it turns out, most of the time (obviously, it depends on the language, compiler, etc.), it is not.

+27
optimization boolean
Jul 01 '09 at 16:20
source share
14 answers

The compiler should generate the same code. However, a comparison with the true is probably better, because it is more explicit. Usually I do not make an explicit comparison, but you should not make fun of him for it.

Edit: The easiest way to say is to try. The MS compiler (cl.exe) generates the same number of steps in the assembly:

 int _tmain(int argc, _TCHAR* argv[]) { bool test_me = true; if (test_me) { 004113C2 movzx eax,byte ptr [test_me] 004113C6 test eax,eax 004113C8 je wmain+41h (4113E1h) printf("test_me was true!"); } if (test_me == true) { 004113E1 movzx eax,byte ptr [test_me] 004113E5 cmp eax,1 004113E8 jne wmain+61h (411401h) printf("still true!"); } return 0; } 

The question at the moment is that the test and cmp have the same cost? I think so, although experts may point out differences.

Bottom line: you don't have to worry about that. Most likely, you have a way to increase the productivity of fish to fry.

+13
Jul 01 '09 at 16:23
source share

I would expect the difference to be optimized by any semi-similar compiler.

(I just checked with C #, and the compiled code for both syntaxes is exactly the same.)

+16
Jul 01 '09 at 16:21
source share

I think a comparison with the truth shows a lack of understanding by your partner. Bools should be called things to avoid this (for example, isAvaliable : if (isAvailable) {...} ).

+16
Jul 01 '09 at 16:24
source share

Duplicate question ( Should I use `! IsGood` or` IsGood == false`? ). Here's a pointer to my previous answer:

A testing technique specifically against true or false is bad practice if the variable in question is really intended to be used as a logical value (even if its type is not logical) - especially in C / C ++. Testing against true can (and probably will) lead to subtle errors.

See the following SO answer for more details:

Should I use`! IsGood` or `IsGood == false`?

Here is a thread explaining in detail why "== true" is often false in more detail, including Straustrup's explanation: https://qt-project.org/forums/viewthread/32642

+10
Jul 01 '09 at 16:38
source share

Here's a Python parsing (2.6):

 >>> def check(x): return (bool(x) == True) >>> import dis >>> dis.dis(check) 1 0 LOAD_GLOBAL 0 (bool) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 LOAD_GLOBAL 1 (True) 12 COMPARE_OP 2 (==) 15 RETURN_VALUE >>> def check2(x): return bool(x) >>> dis.dis(check2) 1 0 LOAD_GLOBAL 0 (bool) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE 

I believe the reason for check not optimized due to the fact that Python is a dynamic language. This in itself does not mean that Python uses a bad compiler, but it may be worth it to draw a little type inference here. Maybe it matters when the .pyd file is created?

+4
Jul 01 '09 at 16:28
source share

In my experience, if (flag==true) is bad practice.

The first argument is academic:

If you have a bool flag , it is either true or false .

Now expression

 (flag==true) 

again, true or false - it is not more expressive, only redundant - flag cannot get "more truthful" or "more false" than it already is. This would be “clearer” only if it is not obvious. flag is logical, but there is a standard way to fix what works for all types: choose the best name.

Stretching this for no reason, the following would be “even better”:

 ((flag==true)==true) 

The second argument is pragmatic and platform specific.

C and earlier versions of C ++ did not have a real "bool" type, so there are various conventions for flags, the most common of which is that nonzero is true. Often, an API returns a BOOL type based on an integer, but does not ensure that the return value is 0 or 1.

Some environments use the following definitions:

 #define FALSE 0 #define TRUE (!FALSE) 

good luck with if ((1==1) == TRUE)

In addition, some platforms use different values ​​- for example, VARIANT_BOOL for VB interop is short , and VARIANT_TRUE is -1 .

When mixing libraries using these definitions, explicit comparisons to true can easily be a mistake disguised as good intentions. So, no need.

+4
Jul 04 '09 at 20:06
source share

The MSVC ++ 6.0 compiler generates slightly different code for two forms:

 4: if ( ok ) { 00401033 mov eax,dword ptr [ebp-8] 00401036 and eax,0FFh 0040103B test eax,eax 0040103D je main+36h (00401046) .... 7: if ( ok == true ) { 00401046 mov ecx,dword ptr [ebp-8] 00401049 and ecx,0FFh 0040104F cmp ecx,1 00401052 jne main+4Bh (0040105b) 

The former version should be very slightly faster if I remember my 8086 timings correctly :-)

+2
Jul 01 '09 at 16:25
source share

It falls into certain languages ​​and what they consider to be “true” meanings. There are two things in common: JavaScript and PHP .

The triple is equal to the operator in both of these languages, ensures that you are really checking the logical type of truth. For example, checking PHP for if ($value) may be different from if ($value==true) or if ($value===true) :

 $f = true; $z = 1; $n = null; $a = array(1,2); print ($f) ?'true':'false'; // true print ($f==true) ?'true':'false'; // true print ($f===true) ?'true':'false'; // true print "\n"; print ($z) ?'true':'false'; // true print ($z==true) ?'true':'false'; // true print ($z===true) ?'true':'false'; // false print "\n"; print ($n) ?'true':'false'; // false print ($n==true) ?'true':'false'; // false print ($n===true) ?'true':'false'; // false print "\n"; print ($a) ?'true':'false'; // true print ($a==true) ?'true':'false'; // true print ($a===true) ?'true':'false'; // false print "\n"; print "\n"; 

I expect the languages ​​that everyone speaks daily to report how one of them addresses this issue.

+2
Jul 01 '09 at 16:28
source share

The syntax "boolCheck == true" may have some justification, depending on the name of the variable being tested.

For example, if the variable name was "state", you can either:

 if (state) { ... } 

or you can have

 if (state == true) { ... } 

In this case, I think the latter form is more clear and obvious.

Another example would be a variable of type "enabled", in which case the first form becomes more understandable.

Now, having a boolean variable called “state” is bad practice, but you may not have any control over this, in which case the == true syntax can improve code readability.

+2
Jul 01 '09 at 16:39
source share

It depends on the compiler. There may be optimizations for both cases.

+1
Jul 01 '09 at 16:22
source share

Testing for equality with true can lead to an error, at least in C: in C, if "can be used for integer types (and not just logical types)) and take any non-zero value; however, the symbol" TRUE "is one specific non-zero value (e.g. 1 ). This can become important with bit flags:

 if (flags & DCDBIT) { //do something when the DCDBIT bit is set in the flags variable } 

So, such a function is given ...

 int isDcdSet() { return (flags & DCDBIT); } 

... the expression "if (isDcdSet ())" does not match "if (isDcdSet () == TRUE)".

Anyway; I would think that an optimizing compiler should optimize any difference (because there is no logical difference), assuming that it is a language with a true Boolean (not just integer) type.

+1
Jul 01 '09 at 16:34
source share

There is no logical difference, assuming that there is no internal machine simulation, for example, fstream testing.

 ifstream fin; ... if( ! fin) ... 
0
Jul 01 '09 at 16:22
source share

Perhaps this is not the case if you are working with a nullable bool.

Example:

 Bool? myBool = true if(myBool) // This will not compile if(myBool == true) //this will compile 
0
Jul 01 '09 at 16:37
source share

IMHO this is a bad idea to use the if (boolCheck == true) form for a simple reason: if you accidentally type one equals sign instead of a double (i.e. if (boolCheck = true) ), it will assign true to boolCheck and will always return true, which will obviously be a mistake. Of course, most modern compilers will show a warning when they see that (at least the C # compiler), but many developers simply ignore the warnings ...

If you want to be explicit, you should prefer this form: if (true == boolCheck) . This will avoid accidentally assigning a variable and cause a compilation error if you forget the equal sign.

0
Oct 15 '09 at 23:59
source share



All Articles