C++ Operator Precedence
In this page:
Arithmetic Operator Precedence
C++ applies the same order-of-operations rules taught in basic math: multiplication and division are evaluated before addition and subtraction, so 2 + 3 * 4 evaluates to 14, not 20. Misjudging precedence is a common source of subtly wrong calculations that compile without any error.
Example: Arithmetic Operator Precedence
#include <iostream>
int main() {
int result = 2 + 3 * 4;
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Using Parentheses to Force Precedence
Wrapping part of an expression in parentheses forces it to be evaluated first, overriding the default precedence rules entirely — (2 + 3) * 4 evaluates to 20 precisely because the addition is now grouped explicitly. When in doubt about how an expression will be evaluated, adding parentheses costs nothing and removes all ambiguity for both the compiler and future readers.
Example: Using Parentheses to Force Precedence
#include <iostream>
int main() {
int result = (2 + 3) * 4;
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Relational and Logical Precedence
Relational operators like > and < bind more tightly than logical operators like && and ||, which is why a > 5 && b < 10 is parsed as (a > 5) && (b < 10) without needing explicit parentheses around each comparison. Relying on this default ordering without parentheses is fine for simple conditions, but larger expressions benefit from explicit grouping for clarity.
Example: Relational and Logical Precedence
#include <iostream>
int main() {
int a = 6, b = 5;
bool result = a > 5 && b < 10;
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Left-to-Right Associativity
When two operators share the same precedence level, such as a - b + c, C++ evaluates them left to right, treating it as (a - b) + c. This left-to-right rule is what most arithmetic and comparison operators follow, and it matches the way you'd naturally read the expression.
Example: Left-to-Right Associativity
#include <iostream>
int main() {
int a = 10, b = 3, c = 2;
int result = a - b + c;
std::cout << result << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Right-to-Left Associativity of Assignment
Assignment is an exception to left-to-right evaluation — it associates right to left, which is exactly what makes chained assignment like a = b = c = 0; work: c = 0 happens first, then that result is assigned to b, and finally to a. This lets you initialize several variables to the same value in one compact line.
Example: Right-to-Left Associativity of Assignment
#include <iostream>
int main() {
int a, b, c;
a = b = c = 5;
std::cout << a << " " << b << " " << c << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: