Programming Tip Of The Day #2 – Difference Between i++ and ++i

To some, this should seem a bit obvious and if I am insulting your intelligence by discussing it, I am sorry.  But, one of the main reasons I want to discuss this topic is, I was asked this question in a job interview for Lockheed Martin.

What is the difference between i++ and ++i?

The answer is actually quite simple.

i++ first evaluates the value of i and then increments it

++i increments the value of i and then evaluates it

Here is a brief example to demonstrate what I mean.

// Example: i++ 
$i = 5;
echo "The value of i is " . $i++ ;
// Output "The value of i is 5"
// i = 6
 
// Example: ++i 
$i = 5;
echo "The value of i is " . ++$i;
// Output "The value of i is 6"
// i = 6

So, now if you are ever asked about this in an interview, you will have a response.

Happy programming!

Tags: , , ,

2 comments

  1. Hah! Good one man, one of those fundamental things that i would have totally failed… Forget these things with modern languages.

  2. What utterly useless information. If you don’t know this, you should not be applying for a job as a developer. If you are asked this question in an interview, you don’t want the job, and if you post this as information, well… you shouldn’t be setting yourself up as any kind of expert.

Leave a comment