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
Pre-increment and Post-increment concept in C/C++?
Both pre-increment and post-increment are used to represent the expression of increasing a value by adding 1. Their behavior are different because pre-increment (++i) increases the value before it is used in an expression, while post-increment (i++) increases it after.
Below is the key-terms of pre-increment and post-increment in C/C++:
- Pre-increment (++i) : Before assigning the value to the variable, the value is incremented by one.
- Post-increment (i++) : After assigning the value to the variable, the value is incremented.
Syntax of Using Pre and Post Increment Operators
The following is the basic syntax of pre-increment and post-increment in C/C++:
// Pre-increment ++variable_name; // Post-increment variable_name++;
Here,
- variable_name : This is name of the variable given by user.
Pre Increment Operator (x++)
Pre-increment operator increments the value of a variable by 1 before it is used in the expression.
Example
Here, 'x' is 5, then 'y' will be 6 because 'x' is increased before it's used in the expression:
#include <stdio.h>
int main() {
int x = 5;
int y = ++x;
printf("Value of x: %d\n", x);
printf("Value of y: %d\n", y);
return 0;
}
The above program produces the following result:
Value of x: 6 Value of y: 6
#include <iostream>
using namespace std;
int main() {
int x = 5;
int y = ++x;
cout << "Value of x: " << x << endl;
cout << "Value of y: " << y << endl;
return 0;
}
The above program produces the following result:
Value of x: 6 Value of y: 6
Post Increment Operator (x++)
Post-increment operator increments the value of a variable by 1 after using it in the expression.
Example
In this program, y is assigned the value of x before it is incremented because the post-increment operator (x++) is used.
#include <stdio.h>
int main() {
int x = 5;
int y = x++; // Post-increment: y is assigned x (5), then x is incremented
printf("Value of x: %d\n", x);
printf("Value of y: %d\n", y);
return 0;
}
The above program produces the following result:
Value of x: 6 Value of y: 5
#include<iostream>
using namespace std;
int main() {
int x = 5;
int y = x++; // y gets 5, then x becomes 6
cout << "Value of x: " << x << endl;
cout << "Value of y: " << y << endl;
return 0;
}
The above program produces the following result:
Value of x: 6 Value of y: 5
Now, let us look into the tabular structure of pre-incremental and post-incremental to remember the concept:
| Operation | Before | Result | After x |
|---|---|---|---|
| ++x | 5 | 6 | 6 |
| x++ | 5 | 5 | 6 |