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

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

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

Operator Symbol Form Operation
Prefix increment ++ ++x Increment x, then evaluate x
Prefix decrement –– ––x Decrement 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不??

你可能感兴趣的:(effect)