简体   繁体   中英

C++ Operator precedence and the return statement

If I do something like return a ? b : c; return a ? b : c; or return a && a2 && a3;

Could it ever be evaluated as just return a and then the function just returns immediately before evaluating the rest?

return is a statement , not an expression . So it can never be misinterpreted the way you think.

The statement is always of the form return [some expression]; (and the expression is optional). The expression, if present, is evaluated first, and its value is bound to the return value of the function.

To make this clearer I'm going to restate the question a little:

return a ? b() : c();

return a && a2() && a3();

In the first case, one of either b or c will be called but not the other.

In the second case, if a is false then neither a2 nor a3 will be called. If a2 returns false, a3 won't be called.

In return a && a2 && a3; , if a is false, there's no need to evaluate the rest of the expression. The result will always be false. So a2 and a3 will not be evaluated. This is called "short circuiting".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM