hey guys.
i cant remember for the life of me what the difference is between putting ++ before or after a variable (specifically an int). for example in a for loop.

Using the incrementor before a variable will first increment the value of the variable and then use this value.

Using the incrementor after a variable will use the current value of the variable, and then increment the variable after.

This is generally just a shortcut or "code-condenser". If the syntax is confusing, play around with it, and put brackets so you remember what is going on :).

For example:

int ctr = 0;
while (ctr++ < 10);

The above loop will test the current value of ctr, then increment it. That is, the first test will be ctr = 0, 0 < 10, then 1 < 10, and so on. EDIT: So if you wanted to print the value of ctr after each iteration, you would print 1, 2, ... , 10.

As opposed to this:

int ctr = 0;
while (++ctr < 10);

We will first increment ctr in this case, and use this incremented value to test if less than 10. That is, the first test will be ctr = 1, 1 < 10, then 2 < 10, etc. EDIT: So if you printed the value of ctr in each iteration, you would print 1, 2, ... , 9.

Hope that helps?

++variable means that the variable is incremented by one and the new value is returned. variable++ means that the variable is incremented by one and the old value is returned:

#include <iostream>

int main()
  int variable = 0;

  std::cout << ++variable << '\n'; // Prints 1
  std::cout << variable++ << '\n'; // Also prints 1
  std::cout << variable << '\n'; // Prints 2

If you're not using the returned value in the same expression, it doesn't really matter which one you use. Like in a for loop, both of these do the same thing:

for (int i = 0; i < 10; i++)
  std::cout << i << '\n';
for (int i = 0; i < 10; ++i)
  std::cout << i << '\n';

But, later on you might start caring about the performance of variable++ if the variable isn't a built-in type like int. For example, if you're using an iterator object, it's possible that variable++ is slower than ++variable, and then it's a good idea to use ++variable. This isn't a problem with built-in types because the compiler will optimize them into the same thing if the returned value isn't used.

This would have been very easy for you to test yourself, just made a quick test program:

int i = 5;
cout << i++; // Still 5
int i = 5;
cout << ++i; // Now 6
This article has been dead for over six months. Start a new discussion instead.