I haven’t really understood the difference between

i++ and ++i

  • @N0b3d
    link
    63 years ago

    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.

    • @freely
      link
      63 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.