多个自增自减问题的和

img

img


为什么同样的代码运算结果又不一样
#include<stdio.h>
int main()
{
int i=5,j=5;
int p,q;
p=(i++)+(i++)+(i++);
q=(++j)+(++j)+(++j);
pritf("%d,%d",p,q);
return 0;
}
这个p,q到底怎么算,为什么我算出来的是18,21

img

为什么我算出来

不要写这种代码,你写的这种代码属于undefined behaviour。C/C++标准没有规定运算符操作数的计数顺序,因此不同编译器得到结果不一样。
https://en.cppreference.com/w/cpp/language/eval_order

Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified (with some exceptions listed below). The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.

千万不要计较这个问题,这是未定义行为不同编译器结果都不一样,再说这玩意也没有意义,现实中不可能写出这样的代码。