Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post-increment and Pre-increment concept?

I don't understand the concept of postfix and prefix increment or decrement. Can anyone give a better explanation?

like image 567
Saad Masood Avatar asked Dec 15 '10 00:12

Saad Masood


People also ask

What is post increment and pre increment?

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.

What is ++ i and i ++ in C?

++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.

Which concept is used by pre increment?

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.

What is post increment?

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.


1 Answers

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.

like image 61
Cheers and hth. - Alf Avatar answered Sep 22 '22 16:09

Cheers and hth. - Alf