printf(%d,%dn,i++,++i)的输出结果是确定的吗
1. 问题描述
以下代码的输出结果是什么?
题⽬1:
int i=10;
printf("%d, %d\n", i++, ++i);
题⽬2:
int i = 3;
printf("%d, %d, %d, %d, %d\n", i++, ++i, i, i++, i);
2. 解题思路【错误】
  printf参数是从右⾄左⼊栈的,故:
题⽬1的输出为:11,12
题⽬2的输出为:
3. 反思
printf输出格式%b
注意:该类题⽬编译器不⼀样,结果就会不⼀样,即这种⾏为依赖编译器不必纠结。
原因分析:
C/C++语⾔没有规定具体压栈顺序,没有标准化时C语⾔⽀持没有固定参数的函数,所以为了实现这个当时多数编译器都采⽤从右往左压栈,但是标准化的要求⾄少有⼀个固定参数,这个限制就没有必要了。不过从右到左⼏乎已经成为了C编译器惯⽤的顺序。C++的_stdcall⽅式也是采⽤从右到左,不同的只是不需要调⽤者⾃⼰⼿动清栈。
另外求值顺序和压栈顺序是两回事,C语⾔⾥⼏乎没有对求值顺序做规定,编译器完全可以先求出值再决定如何压栈。
简单说,这种问题与编译器实现语⾔的规定有关。不同编译器下⽣成的代码可能不同,出现的结果就不同。对于这种可能造成错误的代码,不⽤纠结。
What's the value of i++ + i++?
It's undefined. Basically, in C and C++, if you read a variable twice in an expression where you also write it, the result is undefined. Don't do that. Another example is:
v[i] = i++;
Related example:
f(v[i],i++);
Here, the result is undefined because the order of evaluation of function arguments are undefined.
Having the order of evaluation undefined is claimed to yield better performing code. Compilers could warn about such examples, which are typically subtle bugs (or potential subtle bugs). I'm disappointed that after decades, most compilers still don't warn, leaving that job to specialized, separate, and underused tools.