Increment and decrement operator

Using increment and decrement operators, we can increment the value of a variable by 1 or decrement by 1.


Example

int a = 5;

++a;

//After the above statement execution, the value of a will be 6.

int b = 10;

--b;

//After the above statement execution, the value of b will be 9.




A++ vs a+1

You might think why do we need ++ operator to increment variable value by 1. we can achieve this using a=a+1.

You are right. Program level it won’t make any difference. Both will give the same result. But In assembly level some optimizations are there.

a = a + 1;

If you give a = a + 1;

It will load the value a into memory.

And add 1 to a.

And then store it again to a.

It will take three CPU cycles.

a++;

But if you give a++,

Its straight forward in assembly level. It’s just increment a value by 1. We can save some CPU cycles.

Some compilers optimize it smartly now a day.





Example Program

Example

#include<stdio.h>

int main()
{
     int a = 5;

     a++;
     printf("After Increment, a = %d\n",a); //now a will be 6
     a--;
     printf("After Decrementing, a = %d\n",a); // now a will be 5

     return 0;
}


Topics You Might Like