post/pre increment与post/pre decrement的简易理解

来源:互联网 发布:怎么设置网络节点 编辑:程序博客网 时间:2024/05/16 11:49

这个两个东西虽然非常简单,在C++和JAVA当中都有清楚的解释,但是我写下这个文章,纯粹是为了初学者便于理解。Think in Java关于这个知识点的论述原文如下:,因为英文很简单我就不翻译了,只是做一点点解释。

There are two versions of each type of operator, often called the prefix and postfix versions. 

Preincrement means the ++ operator appears before the variable, and post-increment 
means the ++ operator appears after the variable. Similarly, pre-decrement means the -- 
operator appears before the variable, and post-decrement means the -- operator appears 
after the variable. For pre-increment and pre-decrement (i.e., ++a or --a), the operation is 
performed and the value is produced. For post-increment and post-decrement (i.e., a++ or 
a--), the value is produced, then the operation is performed. As an example:  
//: operators/AutoInc.java // Demonstrates the ++ and -- operators. import static net.mindview.util.Print.*;  public class AutoInc {   public static void main(String[] args) {     int i = 1;     print("i : " + i);     print("++i : " + ++i); // Pre-increment     print("i++ : " + i++); // Post-increment     print("i : " + i);     print("--i : " + --i); // Pre-decrement     print("i-- : " + i--); // Post-decrement     print("i : " + i);   } } /* Output: i : 1 ++i : 2 i++ : 2 i : 3 --i : 2 i-- : 2 i : 1 *///:~ 
print("++i : " + ++i); // Pre-increment 可以看作是两行代码:
i=i+1;
print(i);
而print("i++ : " + i++); // Post-increment
可以看作如下两行代码:
print(i);
i=i+1;