C ++ Order of evaluating subexpressions with boolean operators

There are many questions about the concepts of priority and order of evaluation , but I could not find one that links to my special case.

Consider the following statement:

if(f(0) && g(0)) {};

      

Is f (0) guaranteed to be evaluated first? Note that the & & operator.

My confusion stems from what I read in "The C ++ Programming Language (Stroustrup, 4ed, 2013)".

Section 10.3.2 of the book says:

The order of evaluation of <strong> subexpressions in an undefined expression . In particular, you cannot assume that an expression is evaluated from left to right. For example:

int x = f (2) + g (3); // undefined is f () or g () called first

This is similar to all operators , including the && & operator, but the next paragraph says:

Operators, (comma), && (boolean and) and || (boolean or) ensure that their left operand is evaluated before their right operand.

It is also mentioned in section 11.1.1:

& & and || operators evaluate their second argument only when necessary, so they can be used to control the order of evaluation (ยง10.3.2). For example:

while (p &! whitespace (p)) ++ p;

Here p is not dereferenced if it is nullptr.

This last quote means && and || evaluate their first argument first, so this seems to confirm my assumption that the operators mentioned in the second quote are exceptions from the 1st quote, but I cannot make a definitive conclusion from this last example since the expression contains only one subexpression unlike my example which contains two .

+3


source to share


2 answers


Special sequencing behavior &&

, ||

and is ,

well known in C and C ++. The first sentence you quoted should say, "The order in which subexpressions are evaluated in an expression is generally undefined" or "With a few exceptions, the order in which subexpressions are evaluated in an expression is not defined."

You asked about C ++, but this question on the C FAQ list is appropriate.




Addendum: I just realized that "not defined" is a better word in these rules than "not defined". Writing something like f() + g()

doesn't give you undefined behavior. You simply have no way of knowing if you can call f

or first g

.

+4


source


Yes, it is guaranteed to f(0)

be fully appreciated first.



This supports a behavior known as short-circuiting, in which we don't need to call the second function at all if the first returns false

.

+2


source







All Articles