变量前后的增量操作在TC和gcc上给出不同的输出 [英] pre and post increment operations on a variable give different output on TC and gcc

查看:98
本文介绍了变量前后的增量操作在TC和gcc上给出不同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 #include  


int main()
{
int i = 5;
printf(%d%d%d%d%d,i ++,i - ,++ i, - i,i);
返回0;

$ / code $ / pre
$ b $ p在gcc上,输出为'4 5 5 5 5' p>

但是在TC上,它输出为'4 5 5 4 5'



我知道在printf语句,如果它是一个表达式,评估将从左到右,但在正常语句中,它将从左到右。



但是如果printf包含多个表达式,则评估将在堆叠上进行,元素将从左到右推入堆叠,但从右向左弹出,并证明TC输出是正确的。



请纠正我在哪里我错了???

解决方案

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

这篇关于变量前后的增量操作在TC和gcc上给出不同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆