
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What is the difference between prefix and postfix operators in C++?
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, however, the {value|the worth} of the expression is that the original value of i. So basically it first assigns a value to expression and then increments the variable.
Let's look at some code to get a better understanding −
Example
#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
- Related Articles
- Difference between prefix and postfix operators in C#?
- Differentiate between the prefix and postfix forms of the ++ operator in java?
- Prefix and Postfix Expressions in Data Structure
- What are postfix operators in C++?
- What are postfix operators in C#?
- What is the difference between | and || operators in c#?
- What is the difference between >> and >>> operators in Java?
- What is the difference between = and == operators in Python?
- What is the difference between = and: = assignment operators?
- What is the difference between the != and operators in Python?
- Precedence of postfix ++ and prefix ++ in C/C++
- Prefix to Postfix Conversion in C++
- What is the difference between the | and || or operators in C#?
- what is the main difference between '=' and '==' operators in javascript?
- What is difference in Python operators != and "is not"?

Advertisements