What is the difference between ++i and i++ in C++? (2024)

Table of Contents
Example Output

There is a big distinction between the suffix and prefix versions of ++.

  • In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i. So basically it first increments then assigns a value to the expression.
  • In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i. So basically it first assigns a value to 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++; z = ++x; cout << x << ", " << y << ", " << z; return 0;}

Output

This would give us the output −

5, 3, 5

Why is this? Let's look at it in detail −

  • Initialize x to 3
  • Assign y the value we get by evaluating the expression x++, ie, the value of x before increment then increment x.
  • Increment x then assign z the value we get by evaluating the expression ++x, ie, value of x after the increment.
  • Print these values
Kickstart Your Career

Get certified by completing the course

Get Started

What is the difference between ++i and i++ in C++? (31)

Advertisem*nts

'; adpushup.triggerAd(ad_id); });

What is the difference between ++i and i++ in C++? (2024)
Top Articles
Latest Posts
Article information

Author: Domingo Moore

Last Updated:

Views: 6151

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Domingo Moore

Birthday: 1997-05-20

Address: 6485 Kohler Route, Antonioton, VT 77375-0299

Phone: +3213869077934

Job: Sales Analyst

Hobby: Kayaking, Roller skating, Cabaret, Rugby, Homebrewing, Creative writing, amateur radio

Introduction: My name is Domingo Moore, I am a attractive, gorgeous, funny, jolly, spotless, nice, fantastic person who loves writing and wants to share my knowledge and understanding with you.