I'm having trouble figuring out whats the difference of using them prefix and postfix.
What times would I need to use both of those operations?
Printable View
I'm having trouble figuring out whats the difference of using them prefix and postfix.
What times would I need to use both of those operations?
Simple. The prefix increment/decrement operators return the incremented/decremented value, while the postfix returns the original value. That is to sayQuote:
Originally Posted by Syllable
Code:int x = 5;
std::cout << x++; // Will output '5'
It's generally better to use the prefix, as it takes less time to resolve (it doesn't have to store the original value temporarily), unless the situation arises where you need the pre-updated value to resolve in the next operator. For instance, in the subscript operator.Code:int x = 5;
std::cout << ++x; // Will output '6'
Code:while(x < 10)
std::cout << arry[x++];
Oh, and to the OP, one thing you should learn never to do with increments:
That is, you can't have two things which both modify the same value in a single expression. Incrementing is a common cause (although function calls can do it too).Code:int x = 5;
std::cout << x++ << " " << ++x; // Will output whatever the heck it feels like (the behavior is undefined).
What Cat mentioned is a quirk of sequence points.