Table of contents
Definition
Some programming languages provide short code for increase or decrease value. By using the prefix and postfix operators, you can write code faster.
Purpose
Thus, i=i+1 is same as i+=1 is same as i++ and ++i. But, what is difference between prefix operator (++i) and postfix operator (i++)?
Inner code
code | name | How |
++i | prefix increment operator | i = i+1; return i; |
i++ | postfix increment operator | final int t = i; i = i+1; return t; |
--i | prefix decrement operator | i = i-1; return i; |
i-- | postfix decrement operator | final int t = i; i = i-1; return t; |
Example 1
int x = 2;
int y = 2;
System.out.println(x * y++); //4
System.out.println(x); //2
System.out.println(y); //3
Because i++ happens after run the code,
- run $$ x \cdot y $$
- print $$ x \cdot y=2 \cdot 2=4 $$
- add 1 to y $$ 1 + y $$
Example 2
int x = 2;
int y = 2;
System.out.println(x * ++y); //6
System.out.println(x); //2
System.out.println(y); //3
Because ++i happens before run the code,
- add 1 to y $$ 1 + y $$
- run $$ x \cdot y $$
- print $$ x \cdot y=2 \cdot 3=6 $$
conclusion
- ++i wil give you slightly better speed and memory.
- If you are working with backend(such as Java), this is not important. However, if you are working with console games(such as C++), this is important.
- i++ will happen after run the code
- ++i will happen before run the code