
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements