I'm currently learning C++ and I've learned about the incrementation a while ago. I know that you can use "++x" to make the incrementation before and "x++" to do it after.
Still, I really don't know when to use either of the two... I've never really used "++x" and things always worked fine so far - so, when should I use it?
Example: In a for loop, when is it preferable to use "++x"?
Also, could someone explain exactly how the different incrementations (or decrementations) work? I would really appreciate it.
I agree with @BeowulfOF, though for clarity I would always advocate splitting the statements so that the logic is absolutely clear, i.e.:
or
So my answer is if you write clear code then this should rarely matter (and if it matters then your code is probably not clear enough).
Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.
"More Effective C++" item #6 - that's sufficient authority for me.
For those who don't own the book, here are the pertinent quotes. From page 32:
And on page 34:
It's not a question of preference, but of logic.
x++
increments the value of variable x after processing the current statement.++x
increments the value of variable x before processing the current statement.So just decide on the logic you write.
x += ++i
will increment i and add i+1 to x.x += i++
will add i to x, then increment i.I just want to notice that the geneated code is offen the same if you use pre/post incrementation where the semantic (of pre/post) doesn't matter.
example:
pre.cpp:
post.cpp:
_
Example 1:
When multiple values are cascaded with << using cout then calculations(if any) take place from right-to-left but printing takes place from left-to-right e.g., (if val if initially 10)
will result into
Example 2:
In Turbo C++, if multiple occurrences of ++ or (in any form) are found in an expression, then firstly all prefix forms are computed then expression is evaluated and finally postfix forms are computed e.g.,
It's output in Turbo C++ will be
Whereas it's output in modern day compiler will be (because they follow the rules strictly)
expressions vary from compiler to compiler.
From cppreference when incrementing iterators:
Pre-increment does not generate the temporary object. This can make a significant difference if your object is expensive to create.