Question

I only know i = i++; is undefined behavior, but if there are two or more functions called in an expression, and all the functions are the same. Is it undefined? For example:

int func(int a)
{
    std::cout << a << std::endl;
    return 0;
}

int main()
{
    std::cout << func(0) + func(1) << std::endl;
    return 0;
}
Was it helpful?

Solution

The behavior of the expression func(0) + func(1) is defined in that the result will be the sum of the results obtained by calling func with a parameter of 0 and funcwith a parameter of 1.

However, the order in which the functions are called is probably implementation dependent, although it might be unspecified. That is, the compiler could generate code equivalent to:

int a = func(0);
int b = func(1);
int result = a + b;

Or it could generate:

int a = func(1);
int b = func(0);
int result = a + b;

This normally won't be a problem unless func has side effects that depend on the order of calls.

OTHER TIPS

std::cout << func(0) + func(1) << std::endl;

Whether the function call func(0) or func(1) executes first, is implementation dependent. After that, there is a sequence point, and func(0) + func(1) is output.

But by definition, it's not called undefined behavior.

The behavior of this program is not undefined but it is unspecified, if we look at the draft C++ standard section 1.9 Program execution paragraph 15 says(emphasis mine):

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note ] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

and if we check section 5.7 Additive operators which covers + and - that section does not specify an ordering so it is unsequenced.

In this case func has a side effect since it is outputting to stdout and so the order of the output is going to depend on the implementation and it even could change for subsequent evaluations.

Note that the ; ends an expression statement and section 6.2 Expression statement says:

[...]All side effects from an expression statement are completed before the next statement is executed.[...]

so although the order of the function calls is unspecified, the side effects of each statement are completed before the next.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top