[c++] 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?

This question is related to c++ conceptual post-increment pre-increment

The answer is


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.


The difference between the postfix increment, x++, and the prefix increment, ++x, is precisely in how the two operators evaluate their operands. The postfix increment conceptually copies the operand in memory, increments the original operand and finally yields the value of the copy. I think this is best illustrated by implementing the operator in code:

int operator ++ (int& n)  // postfix increment
{
    int tmp = n;
    n = n + 1;
    return tmp;
}

The above code will not compile because you can't re-define operators for primitive types. The compiler also can't tell here we're defining a postfix operator rather than prefix, but let's pretend this is correct and valid C++. You can see that the postfix operator indeed acts on its operand, but it returns the old value prior to the increment, so the result of the expression x++ is the value prior to the increment. x, however, is incremented.

The prefix increment increments its operand as well, but it yields the value of the operand after the increment:

int& operator ++ (int& n)
{
    n = n + 1;
    return n;
}

This means that the expression ++x evaluates to the value of x after the increment.

It's easy to think that the expression ++x is therefore equivalent to the assignmnet (x=x+1). This is not precisely so, however, because an increment is an operation that can mean different things in different contexts. In the case of a simple primitive integer, indeed ++x is substitutable for (x=x+1). But in the case of a class-type, such as an iterator of a linked list, a prefix increment of the iterator most definitely does not mean "adding one to the object".


You should also be aware that the behaviour of postincrement/decrement operators is different in C/C++ and Java.

Given

  int a=1;

in C/C++ the expression

 a++ + a++ + a++

evaluates to 3, while in Java it evaluates to 6. Guess why...

This example is even more confusing:

cout << a++ + a++ + a++ << "<->" << a++ + a++ ;

prints 9<->2 !! This is because the above expression is equivalent to:

operator<<( 
  operator<<( 
    operator<<( cout, a++ + a++ ), 
    "<->"
  ), 
  a++ + a++ + a++ 
)

int i, x;

i = 2;
x = ++i;
// now i = 3, x = 3

i = 2;
x = i++; 
// now i = 3, x = 2

'Post' means after - that is, the increment is done after the variable is read. 'Pre' means before - so the variable value is incremented first, then used in the expression.


From the C99 standard (C++ should be the same, barring strange overloading)

6.5.2.4 Postfix increment and decrement operators

Constraints

1 The operand of the postfix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.

Semantics

2 The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.

3 The postfix -- operator is analogous to the postfix ++ operator, except that the value of the operand is decremented (that is, the value 1 of the appropriate type is subtracted from it).

6.5.3.1 Prefix increment and decrement operators

Constraints

1 The operand of the prefix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.

Semantics

2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1). See the discussions of additive operators and compound assignment for information on constraints, types, side effects, and conversions and the effects of operations on pointers.

3 The prefix -- operator is analogous to the prefix ++ operator, except that the value of the operand is decremented.


int i = 1;
int j = 1;

int k = i++; // post increment
int l = ++j; // pre increment

std::cout << k; // prints 1
std::cout << l; // prints 2

Post increment implies the value i is incremented after it has been assigned to k. However, pre increment implies the value j is incremented before it is assigned to l.

The same applies for decrement.


Post increment(a++)

If int b = a++,then this means

int b = a;

a = a+1;

Here we add 1 to the value. The value is returned before the increment is made,

For eg a = 1; b = a++;

Then b=1 and a=2

Pre-increment (++a)

If int b = ++a; then this means

a=a+1;

int b=a ;

Pre-increment: This will add 1 to the main value. The value will be returned after the increment is made, For a = 1; b = ++a; Then b=2 and a=2.


Post-increment:

int x, y, z;

x = 1;
y = x++; //this means: y is assigned the x value first, then increase the value of x by 1. Thus y is 1;
z = x; //the value of x in this line and the rest is 2 because it was increased by 1 in the above line. Thus z is 2.

Pre-increment:

int x, y, z;

x = 1;
y = ++x; //this means: increase the value of x by 1 first, then assign the value of x to y. The value of x in this line and the rest is 2. Thus y is 2.
z = x; //the value of x in this line is 2 as stated above. Thus z is 2.

No one has answered the question: Why is this concept confusing?

As an undergrad Computer Science major it took me awhile to understand this because of the way I read the code.

The following is not correct!


x = y++

X is equal to y post increment. Which would logically seem to mean X is equal to the value of Y after the increment operation is done. Post meaning after.

or

x = ++y
X is equal to y pre-increment. Which would logically seem to mean X is equal to the value of Y before the increment operation is done. Pre meaning before.


The way it works is actually the opposite. This concept is confusing because the language is misleading. In this case we cannot use the words to define the behavior.
x=++y is actually read as X is equal to the value of Y after the increment.
x=y++ is actually read as X is equal to the value of Y before the increment.

The words pre and post are backwards with respect to semantics of English. They only mean where the ++ is in relation Y. Nothing more.

Personally, if I had the choice I would switch the meanings of ++y and y++. This is just an example of a idiom that I had to learn.

If there is a method to this madness I'd like to know in simple terms.

Thanks for reading.


Since we now have inline javascript snippets I might as well add an interactive example of pre and pos increment. It's not C++ but the concept stays the same.

_x000D_
_x000D_
let A = 1;_x000D_
let B = 1;_x000D_
_x000D_
console.log('A++ === 2', A++ === 2);_x000D_
console.log('++B === 2', ++B === 2);
_x000D_
_x000D_
_x000D_


It's pretty simple. Both will increment the value of a variable. The following two lines are equal:

x++;
++x;

The difference is if you are using the value of a variable being incremented:

x = y++;
x = ++y;

Here, both lines increment the value of y by one. However, the first one assigns the value of y before the increment to x, and the second one assigns the value of y after the increment to x.

So there's only a difference when the increment is also being used as an expression. The post-increment increments after returning the value. The pre-increment increments before.


The pre increment is before increment value ++ e.g.:

(++v) or 1 + v

The post increment is after increment the value ++ e.g.:

(rmv++) or rmv + 1

Program:

int rmv = 10, vivek = 10;
cout << "rmv++ = " << rmv++ << endl; // the value is 10
cout << "++vivek = " << ++vivek; // the value is 11

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to conceptual

Post-increment and Pre-increment concept?

Examples related to post-increment

Post-increment and Pre-increment concept? ++i or i++ in for loops ?? How do the post increment (i++) and pre increment (++i) operators work in Java? Incrementing in C++ - When to use x++ or ++x? Difference between pre-increment and post-increment in a loop? Is there a performance difference between i++ and ++i in C? C: What is the difference between ++i and i++?

Examples related to pre-increment

Post-increment and Pre-increment concept? ++i or i++ in for loops ?? How do the post increment (i++) and pre increment (++i) operators work in Java? Incrementing in C++ - When to use x++ or ++x? Difference between pre-increment and post-increment in a loop? Is there a performance difference between i++ and ++i in C? C: What is the difference between ++i and i++?