passing_through
passing_through

Reputation: 1941

Is the result of indirectly mutating the same value twice per statement undefined?

As far as I know, C++ code like foo(++i, ++i) yields undefined behavior because it mutates i twice per "sequence point" (by the way, what's the new term for it?). But what if the same happens indirectly? Here's an example:

#include <iostream>

unsigned nextId = 0;
struct IdOwner {
  unsigned id;
  IdOwner() : id(nextId++) {} // mutates nextId
};

void test(IdOwner one, IdOwner two) {
  std::cout << one.id << " " << two.id << std::endl; // just observing
}

int main() {
  test(IdOwner{}, IdOwner{}); // indirectly mutates nextId twice per statement
}

Does that call to test() cause undefined behavior? For me it prints 1 0 which is fine (note: the order of computing function arguments is unspecified).

Upvotes: 1

Views: 97

Answers (1)

cigien
cigien

Reputation: 60268

The order of evaluation of function arguments is unspecified. In this call:

test(IdOwner{}, IdOwner{});

the 2 IdOwner objects can be evaluated in any order, but both will be evaluated before the call to test. So the program could print 0 1 or 1 0.

Upvotes: 4

Related Questions