I don't understand the concept of postfix and prefix increment or decrement. Can anyone give a better explanation?
Pre-increment and Post-increment concept in C/C++?Pre-increment (++i) − Before assigning the value to the variable, the value is incremented by one. Post-increment (i++) − After assigning the value to the variable, the value is incremented.
++i will increment the value of i , and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) i++ will increment the value of i , but return the original value that i held before being incremented.
Right Answer is: The pre-increment usually uses the concept of ” call by reference ” as the changes are reflected back to the memory cells/variables.
2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented.
All four answers so far are incorrect, in that they assert a specific order of events.
Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.
So.
For the built-in C++ prefix operator,
++x
increments x
and produces (as the expression's result) x
as an lvalue, while
x++
increments x
and produces (as the expression's result) the original value of x
.
In particular, for x++
there is no no time ordering implied for the increment and production of original value of x
. The compiler is free to emit machine code that produces the original value of x
, e.g. it might be present in some register, and that delays the increment until the end of the expression (next sequence point).
Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With