C ++中的增量 [英] increment in C++

查看:93
本文介绍了C ++中的增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,有没有人可以帮助我?

我有这个简单的程序:



#include< iostream.h>

void main()

{

int A,B = 8;

A = ++ B + + + B;

cout<< A<< B;

}



我预计A的结果将是9 + 10 = 19但是结果是20并且我尝试了很多程序但是我无法理解他们的结果的原因。


可以任何一个解释了我的原因。
谢谢你所有

Hi all, can any one help me?
I have this simple program:

#include<iostream.h>
void main()
{
int A,B= 8;
A = ++B + ++B;
cout<<A<<B;
}

I expected that the result of A will be 9+10 = 19 but the result was 20 and I tried many programs but I couldn't understand the reason of their results.

Can any one explain the reasons for me.
thank u for all

推荐答案

C ++标准(1998)说:

$ / b $ b在前一个和下一个序列点之间,标量对象的表达式评估最多只能修改一次存储值。此外,只能访问先前值以确定值对于完整表达式的子表达式的每个允许排序,应满足本段的要求; oth行为是未定义的。



当您在下一个序列点(终止分号)之前两次修改标量对象(B)时,会发生什么未定义。当某些事情未定义时,所有投注都将被取消 - 编译器可以清除它想要的任何旧垃圾。有时垃圾就是你想要的,但往往不是。



读一读 Angelika Langer的讨论 [ ^ ]的序列点有更多背景。



干杯,



Ash
The C++ standard (1998) says:

"Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined."

As you're modifying the scalar object (B) twice before the next sequence point (the terminating semi-colon) what happens is undefined. When something is undefined all bets are off - the compiler can chuck out any old rubbish it wants. Sometimes the rubbish is what you want but quite often it's not.

Have a read of Angelika Langer's discussion[^] of sequence points for a bit more background.

Cheers,

Ash


你违反了C ++的规则。在同一个变量的单个表达式中多次使用递增/递减会产生无法保证的结果,因为编译器编写者可以以任何他们认为合适的方式自由地评估表达式。你应该使用如下代码块:

You are breaking the rules of C++. Using increment/decrement multiple times in a single expression on the same variable gives results that cannot be guaranteed, as the compiler writer is free to evaluate the expression in any way they see fit. You should use a code block like:
int A,B= 8;
A = ++B;    // A == 9
++B;        // B == 10
A += B;     // A == 19
}


你试过把公式括起来了吗? :

Have you tried bracketing the formula ie. :
A = (B++) + (B++)


这篇关于C ++中的增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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