3.3 自增/自减操作符,和Side effects

from http://www.learncpp.com/cpp-tutorial/33-incrementdecrement-operators-and-side-effects/

一个变量自增1与自减1是如此的平常,以至于在C中它们有了自己的操作符。每一个操作符都有两个版本——前缀与后缀。

OperatorSymbolFormOperation
Prefix increment++++xIncrement x, then evaluate x
Prefix decrement––––xDecrement x, then evaluate x
Postfix increment++x++Evaluate x, then increment x
Postfix decrement––x––Evaluate x, then decrement x

如:

   1: int x = 5;
   2: int y = ++x; // x is now equal to 6, and 6 is assigned to y

 

   1: int x = 5;
   2: int y = x++; // x is now equal to 6, and 5 is assigned to y

 

再举一例来显示前置与后置之间的差别:

   1: int x = 5, y = 5;
   2: cout << x << " " << y << endl;
   3: cout << ++x << " " << --y << endl; // prefix
   4: cout << x << " " << y << endl;
   5: cout << x++ << " " << y-- << endl; // postfix
   6: cout << x << " " << y << endl;

 

结果为:

5 5
6 4
6 4
6 4
7 3

 

Side effects

A side effect is a result of an operator, expression, statement, or function that presists even after the operator, expression, statement, or function has finished being evaluated. 

(能不能解释为,表达式,函数,或语句等求值以后的结果)

如:

   1: x = 5;

 

是有用的。

而:

   1: int x = 5;
   2: int nValue = Add(x, ++x);

 

C++并没有定义函数中哪个参数先被求值。可能产生两种结果:1、Add(5,6)   2、Add(6,6).

一个通用的规则是避免使用会引起类似结果的操作符。所有的赋值操作符、自增自减。会引起side effect的操作符因该放在独立的语句中。

有谁能解释一下side effects不??

转载于:https://www.cnblogs.com/grass-and-moon/archive/2012/05/12/2496984.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值