capypad
0 day streak
cpp / beginner
Snippet

Operator Precedence and Parentheses

Operator precedence determines how expressions are evaluated. Multiplication has higher precedence than addition. Logical AND (&&) has higher precedence than OR (||). Always use parentheses to make your intent clear and avoid bugs.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
 
int main() {
int a = 5, b = 3, c = 8;
 
int result1 = a + b * c;
int result2 = (a + b) * c;
 
bool isValid = (a > 2) && (b < 10) || (c == 8);
 
std::cout << "a + b * c = " << result1 << std::endl;
std::cout << "(a + b) * c = " << result2 << std::endl;
std::cout << "isValid = " << isValid << std::endl;
 
return 0;
}
Breakdown
1
a + b * c
Multiplication evaluated first: b * c = 24, then a + 24 = 29
2
(a + b) * c
Parentheses force addition first: (5+3) = 8, then 8 * 8 = 64
3
(a > 2) && (b < 10)
Comparison operators have lower precedence than arithmetic
4
isValid = ...
Without parentheses, && would bind tighter than ||