前增量和后增量 [英] Pre increment and post increment

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

问题描述

在示例中,我很难理解后递增(++),预递增(--)和加/减运算的作用.

I'm having trouble understanding how Post Increment (++), Pre Increment (--) and addition/subtraction work together in an example.

x++表示将1加到变量中.

x++ means add 1 to the variable.

x--表示从变量中减去1.

x-- means subtract 1 from the variable.

但我对此示例感到困惑:

int x = 2, y = 3, z = 1;`

y++ + z-- + x++;

我认为这表示3(+1) + 1(-1) + 2(+1),这意味着结果应为7.

I assume this means 3(+1) + 1(-1) + 2(+1) Which means the result should be 7.

但是当我编译它时,我得到了6.我不明白.

But when I compile it, I get 6. I don't understand.

int main() {
  int x=2, y=3, z=1;
  int result;

  result = y++ + z-- + x++;    //this returns 6

  cout << result << endl;
  return 0;
}

推荐答案

 result = y++ + z-- + x++;
           3     1      2  = 6

如果您再次执行此操作

 result1 = y++ + z-- + x++;
          4     0      3  = 7

原因

operator++返回原始值,然后递增变量.

operator++ returns the original value, before incrementing the variable.

++operator返回增加的值

--与上面相同,只是其递减量

-- is same as above just its decrement

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

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