Is it legal to use the increment operator in a C++ function call?

前端 未结 8 1415
时光取名叫无心
时光取名叫无心 2020-11-30 01:56

There\'s been some debate going on in this question about whether the following code is legal C++:

std::list::iterator i = items.begin();
while          


        
8条回答
  •  悲&欢浪女
    2020-11-30 02:13

    Quoth the C++ standard 1.9.16:

    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 the different argument expressions are unsequenced.)

    So it would seem to me that this code:

    foo(i++);
    

    is perfectly legal. It will increment i and then call foo with the previous value of i. However, this code:

    foo(i++, i++);
    

    yields undefined behavior because paragraph 1.9.16 also says:

    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.

提交回复
热议问题