c++, evaluating expressions with multiple `&&`s and no operator of lower precedence
Asked Answered
S

3

2

If an expression evaluates multiple && operators, and does not evaluate any operators of lower precedence (eg. ||, ?:), will the expression evaluate to 0 as soon as one of the &&s return 0, or will it finish evaluating the remaining &&s?

For example,

q=0; w=1; e=1; r=1;
if(q && w && r && e) {}

Will this if() evaluate to false as soon as q && w evaluates to 0 (since the remaining && must all evaluate to 0 regardless of the right hand operators)?

Sulfonmethane answered 25/8, 2011 at 19:22 Comment(0)
T
5

Yes, evaluation will terminate early ("short circuit") as soon as a false expression is encountered. There is one exception to this: if the && operator has been overloaded for the relevant types of arguments. This is strongly discouraged and extremely rare, but could happen.

Tenor answered 25/8, 2011 at 19:25 Comment(0)
H
4

Yes, it does do short-circuit evaluation, for built-in types. Custom types where you've overloaded && or || won't have short-circuiting performed, which can cause subtle bugs.

Hildegardhildegarde answered 25/8, 2011 at 19:23 Comment(0)
P
2

Others have already stated the answer (i.e. "yes").

I will answer to add an example of one particularly idiomatic usage of this:

if ((p != NULL) && (*p == 42))
{
    /* Do something */
}

This would have to be written in a much clumsier manner if short-circuiting didn't happen.

Note that you can also use this in a Perl-esque manner, e.g.:

someCondition && doSomething();

so doSomething() only gets called if someCondition is true. But this only compiles if doSomething() returns a type that can be converted to bool, and it's not considered idiomatic C++. (Note also that this technique doesn't compile in C.)

Polluted answered 25/8, 2011 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.