I haven’t really understood the difference between
i++
and ++i
i++ is called a postfix operator.
++i is called a prefix operator.Keep in mind that some operators not only perform an operation, but return a value wherever that expression is used.
So you can create a variable, and set it to the operator like this:
int t = 0++
I believe the only difference in these two operators is what they return.
The prefix operator, (++i) will increment the variable first, and give the value after the increment.
The postfix operator, (i++) will increment the variable afterwards, giving the value before the increment.So for example:
cout << ++0
Prints 1
cout << 0++
Prints 0Correct, but in theory ++ doesn’t have to increment anything. You can create operators on your own classes, so you could create a ++ operator that shoots the cat instead of incrementing a value. C++ is great (and terrible) like that. Therein lies another difference, if memory serves me correctly - one of prefix or postfix may create a possibly unnecessary object (I haven’t used C++ for several years now and so forget which one it is, and can’t be bothered to find out or work it out right now), so is more expensive in terms of memory usage and CPU time.
There is (was?) a great book about C++ called C++ FAQs or something similar, by Marshall & Kline (I think) that goes into all this stuff and is a great read (it’s the most readable textbook I’ve ever come across).
Caveat: my knowledge may well be out of date. The last time I picked up a C++ compiler in anger was around the turn of the century.
Yeah the value copy is necessary to return the old (pre-increment) value with i++. However, your compiler is (usually) smart enough to optimize the copy away if you never use it.
That being said, being explicit is good, so use ++i if you don’t need the old value. Don’t depend on the compiler to maybe do something.
Thanks very much
i++
gives the current value ofi
and then increments it, while++i
increments it and returns the new valuemy understanding…(I’m very new and trying to learn) - is that there would be no difference if that statement (i++; or ++i;) were used alone on a line…am I correct in this?
If both were the only statement, then yes they are equivalent because nothing is being done with the returned value either way. The difference only really matters if you’re using the returned value.
yay! I’m slowly making progress!