C order of operations - foo () + bar () - should foo be called before the line?

In the following code:

int foo(); int bar(); int i; i = foo() + bar(); 

Is this guaranteed by the C standard that foo calls before bar called?

+7
source share
5 answers

No, there is no sequence point with + . There is actually a quote on the Wikipedia page about this that answers your question:

Consider two functions f () and g (). In C and C ++, the + operator is not associated with a point in the sequence, and therefore in the expression f () + g () it is possible that either f () or g () will be executed first.

http://en.wikipedia.org/wiki/Sequence_points

+12
source

This is unspecified, and in the case of C99 the corresponding quote is 6.5 / 3:

Except as noted below (to call the function () , && , || , ?: And commas), the order in which subexpressions are evaluated and the order in which side effects occur are not defined.

In your example, foo() and bar() are subexpressions of the full expression i = foo() + bar() .

The β€œlater” for function calls is not directly relevant here, but for reference it is 6.5.2.2/10:

The order of evaluation of the function pointer, the actual arguments and subexpressions is not specified in the actual arguments, but there is a sequence point before the actual call.

For && it 6.5.13 / 4:

Unlike bitwise binary code and operator, operator guarantees && rating from left to right; after the point the score of the first operand.

Since + not on the list of operators above, && and + are "different" in the same way that && and & "unlike", and that is exactly what you are asking for. Unlike && , + does not guarantee an assessment from left to right.

+7
source

No, it is not. The evaluation order of the arguments to the function and the operator is undefined.

The standard only says that calls to foo and bar cannot alternate, which can happen when evaluating subexpressions without calling functions.

+2
source

No, this is not defined. From K and R p. 200:

the procedure for evaluating expressions, with some exceptions, is undefined, even if subexpressions are associated with side effects. That is, if the definition of an operator does not guarantee that its operands are evaluated in a specific order, the implementation can freely evaluate the operands in any order or even alternate their evaluation.

Page 205 of K and R describes additive operators and does not determine the order of the evaluator of the two operands.

0
source

The correct answer I'm working on is "If order is important, the code is unreachable, no matter what the standard says." If you must evaluate foo () before bar (), I explicitly evaluate foo () before bar (). The basis for this is that not every programmer knows the standards, but those who really don’t know whether the author made the original.

0
source

All Articles