1

Calling f(a,a) in the following code is undefined behavior?

#include <iostream>

int f(int &m, int &n) {
  m++;
  n++;
  return m + n;
}


int main() {
  int a = 1;
  int b = f(a, a);
}
11
  • No. Do you have any reason to thing it would be? If so, it might improve the question if you add that information. Commented Oct 17, 2014 at 18:16
  • No that is not undefined behavior. Although strange, that is completely valid. Commented Oct 17, 2014 at 18:16
  • 1
    But return ++m + ++n; would be. Commented Oct 17, 2014 at 18:17
  • Should 'strict aliasing' figure in the discussion? Commented Oct 17, 2014 at 18:19
  • Are you sure @Jarod42? Why would that be undefined? Commented Oct 17, 2014 at 18:22

2 Answers 2

3

There is no undefined behavior with respect to modifying m and n since the modifications of both variables are sequenced. The modification of m will happen before the modification of n since they are both full expressions and all side effects of a full expression are sequenced before the side effects of the next full expression.

The relevant section of the draft C++ standard is section 1.9 Program execution which says:

Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.8.

and:

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

on the other hand the following:

m++ + n++ ;

is undefined behavior since the the order of evaluation of each sub expression is indeterminately sequence with respect to each other.

Jonathan brings up the issue of strict aliasing but I don't see how the compiler can assume that n and m are not aliasing each other and my experiments on godbolt does not indicate any unexpected aliasing assumptions.

Note, a full expression is:

[...]an expression that is not a subexpression of another expression[...]

Usually the ; denotes the end of a full expression.

Sign up to request clarification or add additional context in comments.

Comments

1

There is no undefined behavior here. a will end up being 3 and b will be 6, consistently.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.