由编译器引起的ambiguty [英] ambiguty caused by compiler

查看:102
本文介绍了由编译器引起的ambiguty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/*on dev-cpp output=10
 visual c++ output=12
 why*/
#include<stdio.h>
#include<conio.h>
int main()
{
   int i,j;
   i=1;
   j=(++i)+(++i)+(++i);
   printf("%d",j);
   getch();
}





[edit]已添加代码块,HTML编码 - OriginalGriff [/ edit]



[edit]Code block added, HTML encoded - OriginalGriff[/edit]

推荐答案

似乎编译器处理它的方式不同。让我们对声明进行划分,并尝试弄明白。

It seems like the compilers handle it differently. Let''s divide the statement and, try to figure it out.

首先,使用前缀增量运算符 - 这意味着增量操作应该在使用 i 。但是,之前有多少?

First, you use the Prefix Increment Operator - which means that the increment operation should occur before the use of the value of i. But, how much before?

似乎第一个编译器在使用它们之前直接递增这些值。因此,由于我们有两个 + 运算符,前两个增量在第一个 + 运算符和第三个增量之前执行在第二个 + 运算符之前执行。给我们的是什么: 3 + 3 + 4 = 10

It seems like the first compiler increments the values directly before they are used. So, as we have two + operators, the first two increments are performed before the first + operator and the third increment is performed before the second + operator. What gives us: 3 + 3 + 4 = 10.

第二个编译器执行整个增量声明的开头。是什么给了我们: 4 + 4 + 4 = 12

The second compiler performs the whole of the increments at the beginning of the statement. What gives us: 4 + 4 + 4 = 12.


区别是因为规范没有正式说当预增量应该发生时:编译器可以自己决定是否要在使用之前或在语句开头之前进行预增量,以使其执行模块受益。

显然,这两个编译器对如何操作有不同的想法!



你真的不应该这样做 - 把它分成几行并让copiler整理任何优化。目前尚不清楚你究竟应该得到什么 - 一种思想可能是应该:

The difference is because the specification does not formally say when the pre-increment should occur: the compiler can decide for itself whether it wants to do the pre-increment immediately before the use or at the beginning of the statement, to the benefit of it''s execution module.
Clearly, the two compilers have different ideas of how to do it!

You really shouldn''t do that - divide it into a couple of lines and let the copiler sort out any optimisations. It is not clear to read that exactly what you should get - one school of thought could be that it "should" be:
2 + 3 + 4 = 9



不是12或10!


not 12 or 10!


这篇关于由编译器引起的ambiguty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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