问题描述
可能重复:结果
Could谁能解释这些不确定的行为,(I = I + + + + I,I = I ++等…)
对于下面的code:
main() {
int i = 1 ;
cout << i << ++i << i++ ;
}
我
为什么会输出为331,而不是什么预期即122?
Why do I get the output as 331 instead of what was expected i.e 122 ?
(同样是的printf
而不是COUT即使我使用的情况?)
( Same is the case even if I use printf
instead of cout ?)
推荐答案
&LT;&LT;
是一种功能,即像的ostream&安培;运营商的LT;≤(ostream的&安培; LHS,RhsType RHS)
。
<<
is a function, namely something like ostream& operator<<(ostream& lhs, RhsType rhs)
.
cout << a;
等同于
operator<<(cout, a);
该函数返回LHS,即收益LHS
, - 所以在上面的例子 COUT
返回
The function returns lhs, that is return lhs
, - so in the above examples cout
is returned.
所以,你的例子
cout << i << ++i << i++ ;
等同于
operator<<(operator<<(operator<<(cout, i), ++i), i++);
的校正的C ++不指定顺序操作执行的增量。这似乎合乎逻辑的你和我,最嵌套先去,但就因为编译器而言它是免费的,只要它喜欢执行增量。这是相同的行为像函数myFunc的(COUT,我+ +,++我,我)
其中,其中增量的计算顺序是不确定的。保证的唯一一件事就是函数内到外进行评估。
Correction C++ does not specify which order the increment operations are performed. It seems logical to you and me that the most nested would go first, but as far as the compiler is concerned it is free to execute the increment whenever it likes. It is the same behaviour as a function like myFunc(cout, i++, ++i, i)
where the order in which the increments are evaluated is undefined. The only thing guaranteed is the functions are evaluated inside to outside.
这篇关于在cout和printf的意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!