Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are fold expressions subject to short-circuiting?

In C++17, are fold expressions subject to short-circuiting when used with && or || as their operator? If so, where is this specified?

like image 230
Sydius Avatar asked May 01 '18 04:05

Sydius


People also ask

Does C use short circuiting?

In imperative language terms (notably C and C++), where side effects are important, short-circuit operators introduce a sequence point – they completely evaluate the first argument, including any side effects, before (optionally) processing the second argument.

What is short circuiting in C expression?

Short-Circuit Evaluation: Short-circuiting is a programming concept in which the compiler skips the execution or evaluation of some sub-expressions in a logical expression. The compiler stops evaluating the further sub-expressions as soon as the value of the expression is determined.

Is or a short circuiting operator?

The || OR operator is also a short-circuit operator. Since OR evaluates to true when one or both of its operands are true , short-circuit evaluation stops with the first true .

What are fold expressions?

A fold expression is an instruction for the compiler to repeat the application of an operator over a variadic template pack. Let's take an example. A very basic one and with a questionable usefulness, but one that illustrates how fold expressions work.


1 Answers

Yes, fold expressions using && or || as the operator can short-circuit, subject to the usual caveat that it happens for the built-in meaning, but not for an overloaded operator function.

The meaning of a fold-expression is defined in [temp.variadic]/9:

The instantiation of a fold-expression produces:

  • ((E_1 op E_2) op ...) op E_N for a unary left fold,

  • E_1 op (... op (E_N_minus_1 op E_N)) for a unary right fold,

  • (((E op E_1) op E_2) op ...) op E_N for a binary left fold, and

  • E_1 op (... op (E_N_minus_1 op (E_N op E))) for a binary right fold.

In each case, op is the fold-operator,....

Since the instantiation of the fold-expression is in terms of an expression containing the operator, all the normal rules for the operator, including overload resolution, order of evaluation, and short-circuiting when a built-in operator, apply.

like image 168
aschepler Avatar answered Oct 20 '22 14:10

aschepler