看了楼上的回答,这种情况应该算是未定义行为,取决于编译器实现。下面补充一些参考:
1) sequence point from wikipedia
在C与C++程序设计语言中,表达式的值依赖于它的子表达式的求值顺序。增加更多的顺序点限制了可能的求值顺序,能保证有一个一致结果。
其中的一个sequence point是函数调用时的函数入口点。函数实参的求值顺序未指定,但顺序点意味着这些实参求值的副作用在进入函数时都已经完成。表达式f(i++) + g(j++) + h(k++),调用f(), g(), h()的顺序未指定,i, j, k的自增顺序也未指定。函数调用f(a,b,c)的实参列表不是逗号运算符,a, b, and c的求值顺序未指定。
C语言的所有sequence point可以参考上面链接,但是可以发现,上面的例子所涉及的关键部分并没有包含确定的sequence point,因此行为时undefined。
gcc有个-Wsequence-point选项可以用来对违反c/c++ sequence point规则而引发的未定义行为进行警告。经过测试,gcc -Wsequence-point 1.c 编译上述代码都会发现下面的警告:
1.c:4:27: warning: operation on ‘i’ may be undefined [-Wsequence-point]
printf("%d %d\n", ++i,++i);
^
-Wsequence-point说明也可以解释楼主的疑惑:
It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.". If a program breaks these rules, the results on any particular implementation are entirely unpredictable.
Since the increment/decrement operator modifies its operand, use of such an operand more than once within the same expression can produce undefined results. For example, in expressions such as x − ++x, it may not be clear to a user in what sequence the subtraction and increment operations should be performed. Such expressions generally invoke undefined behavior, and should be avoided.