Wednesday, August 19, 2009

The ++ operator

In C++ the expression n = n + 1 can be replaced with n++ or ++n. They don't have exactly the same functionality though:

int n = 0;
if( n++ == 1 )
{
     cout << "Hi" << endl;
}

n = 0;
if( ++n == 1 )
{
     cout << "Hello" << endl;
}

Even though n is same after both ifs, only Hello will be printed. The pluses decided whether the value of n is changed before or after the comparison. If we use the ++ preceding the variable then the value will be incremented before the comparison. Care should be taken when using operators like ++. Always try to use a particular one. Prefix ++ is recommended by most persons.


Previous post

Next post




No comments:

Post a Comment