this post was submitted on 24 Aug 2021
3 points (100.0% liked)

C & C++

59 readers
3 users here now

founded 5 years ago
MODERATORS
 

I haven't really understood the difference between

i++ and ++i

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 1 points 3 years ago (1 children)

Correct, 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.

[โ€“] [email protected] 1 points 3 years ago

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.