i++ Vs. ++i
what is difference between prefix operator (++i) and postfix operator (i++)
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
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
- add 1 to 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
- run
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
0 개의 댓글:
댓글 쓰기