Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Difference Between ++i and i++ in C++



There is a big distinction between the suffix and prefix versions of ++. In this article, we will see the differences between them and will go through it's examples.

Prefix version (++i)

In the prefix version (i.e., ++i), the value of i first increments, and then the value of the expression becomes the new value of i.

    So basically it first increments and then assigns a value to the expression.

Postfix version (i++)

In the postfix version (i.e., i++), the value of I first increments, but the value of the expression will be still the original value of i.

    It first assigns a value to an expression and then increments the variable. 

Example

Let's look at some code to get a better understanding ?

#include<iostream>
using namespace std;
int main() {
 int x = 3, y, z;
 y = x++; //Post-increment
 z = ++x; //Pre-increment
 cout << x << ", " << y << ", " << z;
 return 0;
}

Output

We will get the following output.

5, 3, 5

Explanation

Here is the following explanation of the above code.

  • Firstly, initializes x to 3
  • Now, as y = x++, which is post-increment, So first y will get the current value of x that's 3 and then x will upgrade to 4, results y =3 and x=4.
  • Now, in z = ++x, which is pre-increment, So here first x will upgrade and becomes 5 (because it's already upgraded to 4) and then z will get the current value of x, results x = 5 and z = 5.
Updated on: 2024-12-02T00:26:59+05:30

34K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements