繁体   English   中英

快速检查C ++中的增减运算符

[英]Quick check on increment/decrement operators in C++

列出了两个变量声明示例:

范例1:

x = 10;
y = ++x;

范例2:

x = 10;
y = x++;

equals 11, and in Example 2 equals 10. I think I get why and here's my reasoning, so please let me know if I've got this and/or if there's a more concise way of thinking about it. 该书说,在示例1中等于11,在示例2中等于10。我想我知道为什么,这是我的理由,所以请让我知道我是否已经知道和/或是否有更简洁的方法考虑此事。

equals 11 because it's simply set to equal "x + 1" since the increment operator comes first, whereas in the second example is set to be equal to the original declaration of and then the increment operation occurs on separately. 在第一个示例中, 等于11,因为因为增量运算符首先出现,所以将其简单地设置为等于“ x +1”,而在第二个示例中, 设置为等于的原始声明,然后在分开。 . 这似乎是有道理的,因为在示例2中从视觉上看,变量都在等号旁边,然后作为对该方程的事后思考,将发生“ x +1”运算,而对无影响。

你是对的。

y=++x

表示: x++; y=x; x++; y=x;

然而,

y=x++;

表示: y=x; x++; y=x; x++;

我认为您已经掌握了,但是可以用简单的语言来理解。

y = x++;

在此行之后增加x。 结果是

y = 10, x = 11

而在

y = ++x;

在此行之前增加x。 结果是

y = 11, x = 11

黄金法则:

前缀递增/递减(++ x或--x)具有从右到左的关联性。

后缀增减(x ++或x--)具有从左到右的关联性。

x = 10

if (x++ == 11) {        
    // Post increment
}


if (++x == 11 ) {
    // Pre increment
}

因此,在您的情况下:

范例1:

x = 10;
y = ++x;

x的原始值(此处为10)首先递增,然后分配给y。

范例2:

x = 10;
y = x++;

x的原始值首先分配给y,然后递增(到11)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM