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
What does the operation c=a+++b mean in C/C++?
In C, the expression c = a+++b is parsed by the compiler using the "maximal munch" rule, which means it reads the longest possible token sequence. This expression is interpreted as c = (a++) + b, where a++ is the post-increment operator applied to variable a.
Syntax
c = a++ + b; // Post-increment a, then add b c = a + ++b; // Pre-increment b, then add to a
The key difference lies in operator precedence and associativity. The post-increment operator (++) has higher precedence than the addition operator (+), so a+++b is grouped as (a++) + b.
Example 1: Post-increment (a++ + b)
In this example, a is used in its current value for the addition, then incremented afterward −
#include <stdio.h>
int main() {
int a = 2, b = 5;
int c;
printf("Before: a = %d, b = %d\n", a, b);
c = a++ + b; // Same as a+++b
printf("After: a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}
Before: a = 2, b = 5 After: a = 3, b = 5, c = 7
Example 2: Pre-increment (a + ++b)
Here, b is incremented first, then added to a −
#include <stdio.h>
int main() {
int a = 2, b = 5;
int c;
printf("Before: a = %d, b = %d\n", a, b);
c = a + ++b;
printf("After: a = %d, b = %d, c = %d\n", a, b, c);
return 0;
}
Before: a = 2, b = 5 After: a = 2, b = 6, c = 8
Key Points
- The expression
a+++bis always parsed as(a++) + bdue to operator precedence - Post-increment (
a++) uses the current value, then increments - Pre-increment (
++b) increments first, then uses the new value - For clarity, use parentheses to make your intention explicit
Conclusion
The expression c = a+++b in C is interpreted as c = (a++) + b due to operator precedence rules. Understanding increment operators and their timing is crucial for writing predictable C code.
