Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Pre-increment and Post-increment concept in C/C++?
Both pre-increment and post-increment are used to increase a variable's value by 1, but they behave differently in expressions. Pre-increment (++i) increases the value before it is used, while post-increment (i++) increases it after the current expression is evaluated.
Syntax
// Pre-increment ++variable_name; // Post-increment variable_name++;
Key Differences:
- Pre-increment (++i) − Increments the value first, then uses the new value in the expression
- Post-increment (i++) − Uses the current value in the expression, then increments it
Pre-Increment Operator (++x)
The pre-increment operator increments the variable's value by 1 before using it in the expression −
#include <stdio.h>
int main() {
int x = 5;
int y = ++x; // x is incremented first, then assigned to y
printf("Value of x: %d\n", x);
printf("Value of y: %d\n", y);
return 0;
}
Value of x: 6 Value of y: 6
Post-Increment Operator (x++)
The post-increment operator uses the current value in the expression first, then increments the variable −
#include <stdio.h>
int main() {
int x = 5;
int y = x++; // y gets current value of x (5), then x is incremented
printf("Value of x: %d\n", x);
printf("Value of y: %d\n", y);
return 0;
}
Value of x: 6 Value of y: 5
Comparison
| Operation | Initial Value | Expression Result | Final Value |
|---|---|---|---|
| ++x | 5 | 6 | 6 |
| x++ | 5 | 5 | 6 |
Example: Both in Action
#include <stdio.h>
int main() {
int a = 10, b = 10;
printf("Before: a = %d, b = %d\n", a, b);
printf("++a = %d\n", ++a); // Pre-increment
printf("b++ = %d\n", b++); // Post-increment
printf("After: a = %d, b = %d\n", a, b);
return 0;
}
Before: a = 10, b = 10 ++a = 11 b++ = 10 After: a = 11, b = 11
Conclusion
Understanding pre and post-increment is crucial for writing correct C programs. Use pre-increment when you need the incremented value immediately, and post-increment when you need the original value first.
Advertisements
