Popular Posts

이은한. Powered by Blogger.

2022년 2월 6일 일요일

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,

  1. run xyx*y
  2. print xy=22=4x*y=2*2=4
  3. 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,

  1. add 1 to y
  2. run xyx*y
  3. print xy=23=6x*y=2*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

0 개의 댓글:

댓글 쓰기