i = i++; is undefined. Is i = foo(i++) also undefined?

前端 未结 2 1512
太阳男子
太阳男子 2021-02-13 01:37

For example:

int foo(int i) { return i; }

int main()
{
  int i = 0;

  i = i++;      // Undefined
  i = foo(i++); // ?

  return 0;
}

What wou

相关标签:
2条回答
  • 2021-02-13 01:53

    The last sentence in your quote says "that is not otherwise specifically sequenced before or after the execution of the body of the called function" so the question is whether the increment and the assignment are "otherwise specifically sequenced before or after" the function body.

    1.9 [intro.execution] p15 has the answer:

    When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [ Note: Value computations and side effects associated with different argument expressions are unsequenced. — end note ]

    So the increment of i happens before the function body, and the assignment to i happens after the function returns, so it is perfectly well-defined.

    In pre-C++11 terminology, the function call introduces a sequence point between the increment and the assignment.

    0 讨论(0)
  • 2021-02-13 01:55

    i = foo(i++); is fine, because i++ is executed before foo() is called. A copy of i is made, i is then incremented, then the copy is passed to foo(). It is the same as doing this explicitly:

    int tmp = i++;
    i = foo(tmp);
    
    0 讨论(0)
提交回复
热议问题