what is difference between prefix operator (++i) and postfix operator (i++)

what is difference between prefix operator (++i) and postfix operator (i++)

·

2 min read

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

codenameHow
++iprefix increment operatori = i+1;
return i;
i++postfix increment operatorfinal int t = i;
i = i+1;
return t;
--iprefix decrement operatori = i-1;
return i;
i--postfix decrement operatorfinal 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,

  1. run $$ x \cdot y $$
  2. print $$ x \cdot y=2 \cdot 2=4 $$
  3. 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,

  1. add 1 to y $$ 1 + y $$
  2. run $$ x \cdot y $$
  3. 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

Did you find this article valuable?

Support Eunhan's blog by becoming a sponsor. Any amount is appreciated!