且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

变量前后的增量操作在TC和gcc上给出不同的输出

更新时间:2023-11-14 14:23:52

C没有指定应该评估哪个顺序函数参数,所以它是未定义的编译器可以自己选择,包括任意和随机。 Bjarne Stroustrup在C ++编程语言第3版第6.2.2节中明确地说明了这一点。他还给出了一个理由:

 在没有表达式评估顺序限制的情况下可以生成更好的代码


Here is my simple code ...

#include<stdio.h>
int main()
{
int i=5;
printf("%d %d %d %d %d ",i++,i--,++i,--i,i);
return 0;
}

On gcc,it gives output as '4 5 5 5 5'

but on TC,it gives output as '4 5 5 4 5'

what I know that in printf statement,evaluation will be from left to right if it is a single expression but in normal statement,it will be from left to right.

but if printf contain multiple expressions,then evaluation will be on stack,the elements would be pushed onto stack from left to right but popped out from right to left and that justified the TC output

Please correct me where am I wrong ???

C does not specify which order function arguments should be evaluated in, and so it is undefined and a compiler can do it however they choose, including arbitrarily and randomly. Bjarne Stroustrup says this explicitly in "The C++ Programming Language" 3rd edition section 6.2.2

He also gives a reason:

Better code can be generated in the absence of restrictions on expression evaluation order