increment and decrement operators

Most of the people knows increment and decrement operators in programming language very well. Here I am trying to describe it my own way.

Basically both pre(++i) and post(i++) increment operator increase the value of the variable.
both i++ and ++i means
i=i+1;
Now question is if both increase the value of i, what is the difference?

We can understand the difference where we assign(=) or compare(>,<,>=,<=,!,&,&&,|,||, etc) the incremented value with other. We can understand with flowing examples

Example-1: a=i++; (post increment)

lets assume value of i was 5;

so a=i++; means
a=i;
i=i+1;

Many people says i++ means it increase the value of i and return the original value.

So a=i++; means value of a  will be 5 and i will be 6.

Example-2: a=++i; (pre increment)

Lets assume i=5;

so a=++i; means
i=i+1;
a=i;

Many people says ++i means it increase the value of i and return the incremented value.

So a=++i; means value of a  will be 6 and i will be 6.

Advance:

Many people thinks about complex expression like  i=i++ + i++; Here is my suggestion about those expressions

  1. You can explain such expression and get the valid value.like in PHP the above examples value will be 11. But different programming language may produce different answer.But if you know the execution order of the expression of that language(like C,C++ compiler) you can calculate the answer. Many people says this type expression is undefined.
  2. while programming we never write such type of expression so we should not think about those.
  3. We will not write such type expression our whole life,so we don’t need to waste of our time understanding such expression.
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *