-1

锻炼方法是什么:

int i=5;
a= ++i + ++i + ++i;

如果我们按正常的从右到左评估,结果应该是 21 (6 + 7 + 8) 。

我记得在学校学习,答案是 24(8 + 8 + 8)

但我在 CodeBlocks,www.ideone.com 上尝试过,即 gcc 4.8.1 编译器,现在我得到 22。有人可以解释一下原因

4

2 回答 2

0

该表达式中没有序列点,因此您无法解决,它是未定义/编译器相关的。

于 2013-08-05T14:06:39.630 回答
0

它是由 C/C++ 标准定义的未定义或实现定义的行为。语言标准没有指定行为,它允许编译器实现选择(并且通常记录在案)。

还要看看另一个 StackOverflow 问题:谁能解释这些未定义的行为(i = i++ + ++i,i = i++,等等……)


GCC 在您的示例中所做的如下:

int i = 5;
a = ++i + (++i + ++i);  // it first gets the value of i and increments it two times
a = ++i + (7 + 7);  // it then reads the new value of i, does the addition and save it as a constant in the stack
a = ++i + 14;  // it then gets the value of i and increments it
a = 8 + 14;  // it then reads the new value of i and add it to the constant
a = 22;
于 2013-08-05T14:12:42.017 回答