20071116

C++: difference between prefix and suffix increment / decrement.

  • As a prefix : i.e. when the operator precedes the variable (as in ++ i, where i is the integer variable)

If we write:

i1 = 10;
i2 = ++ i1;

This is the same as:

i1 = 10;
i1 = i1 + 1;
i2 = i1;

At the end of these steps the value of both i1 and i2 will be 11. When used as a prefix, the variable is first incremented and later assigned.

  • As a suffix: i.e. when the variable precedes the operator (as in i ++).

If we write:

i1 = 10;
i2 = i1 ++ ;

This is the same as writing:

i1 = 10;
i2 = i1;
i1 = i1 + 1;

At the end of these steps the value of i2 will be 10 and that of i1 will be 11. When used as a postfix, the variable value is first assigned and later incremented.

// suffix
int sum=5; // sum is 5
cout << sum++; // sum is 5. Only in the next reference to sum will it be 6
cout << " " << sum << endl; // sum is now 6

// prefix
sum=5; // sum is 5
cout<<++sum; // sum is immediately 6
cout<<" "<<sum; // sum is 6

Remember: When used as a prefix ( ++i ) compiler will first increment and then assign. When used as a suffix, assignment is done first and then incrementing is performed.

Link: C++ Operators - IV.

Δεν υπάρχουν σχόλια:

eggs.in.art (my non-technical blog)