DEV Community

SwagatikaBehera
SwagatikaBehera

Posted on

Understanding a++ and ++a

lets define it first:
++a here first variable value increment by 1, then value is assigned.(pre increment)

a++ here value of variable is assigned first, then increment by 1.(post increment)

eg: suppose, a = 5
++a = 1 + 5 = 6
a++ = 5 + 1 = 6
It seem to be same, right!

But Its actual difference can be seen in expression,
lets understand with some steps by taking an expression:
eg: a = 5
x = a++ + ++a
steps:
1) 1st evaluate all the pre Operation.
2) Place variable value.
3) Evaluate post Operation.

first, a = 1 + 5 = 6 (because of ++a in 2nd term, a value incremented to 6 from 5 by 1)

second, x = 6 + 6 = 12 (now a value is 6 which we assigned to x)

third, a = 6 + 1 = 7 (because of a++ in 1st term, a value increment to 7 from 6 by 1)

so, x=12 , a=7

Similarly it will happen with decrement operation,
--a here first variable value decrement by 1, then value is assigned.(pre decrement)

a-- here value of variable is assigned first, then decrement by 1.(post decrement)

eg: a = 6
x = a++ + a--
first, no pre Operation.
Second, x = 6 + 6 = 12 (a value is assigned which is 6).
Third, a = 6 + 1 = 7( because of 1st term a++)
7 + (-1) = 6( because of 2nd term a--)

so, x=12 , a=6

eg: a = 6
x = ++a + a-- + --a - a++ + a++
first, a = 1 + 6 = 7
(-1) + 7 = 6
second, x = 6 + 6 + 6 - 6 + 6 = 18
third, a = 6 + (-1) = 5
5 + 1 = 6
6 + 1 = 7

so, x=18 , a=7

eg: a = 6
x = ++a + --a
first, a = 1 + 6 = 7
(-1) + 7 = 6
second, x = 6 + 6 = 12
third, no post operation.

so, x=12 , a=6

eg: given a = 5
find x, y, a
x = a++
y = ++a

x = 5 (first a value is assigned to x and later a will increment by 1, a = 5 + 1 = 6)
y = 1 + 6 = 7 (here first a value increment by 1 then value is assigned)

so, x=5 , y=7 , a=7

Hope you understand completely!

Top comments (0)