0
0
C++programming~5 mins

Operator precedence in C++

Choose your learning style9 modes available
Introduction
Operator precedence tells the computer which math or logic operation to do first when there are many in one line.
When you write math expressions with +, -, *, / together.
When you combine conditions using &&, ||, and ! in if statements.
When you mix assignment (=) with other operations in one line.
When you want to avoid mistakes in complex calculations.
When you want to make your code easier to read by knowing what happens first.
Syntax
C++
expression with multiple operators, e.g. a + b * c - d / e
Operators like * and / have higher precedence than + and -.
Use parentheses () to change the order and make it clear.
Examples
Multiplication (*) happens before addition (+), so 3*4=12, then 2+12=14.
C++
int result = 2 + 3 * 4;
Parentheses change order: 2+3=5 first, then 5*4=20.
C++
int result = (2 + 3) * 4;
&& has higher precedence than ||, so false && false = false, then true || false = true.
C++
bool check = true || false && false;
Parentheses first: true || false = true, then true && false = false.
C++
bool check = (true || false) && false;
Sample Program
This program shows how operator precedence affects math and logic results. Multiplication happens before addition. Logical AND happens before OR. Parentheses change the order.
C++
#include <iostream>

int main() {
    int a = 5, b = 10, c = 2;
    int result1 = a + b * c;  // 5 + (10*2) = 25
    int result2 = (a + b) * c; // (5+10)*2 = 30

    bool val1 = true || false && false; // true || (false && false) = true
    bool val2 = (true || false) && false; // (true || false) && false = false

    std::cout << "result1: " << result1 << "\n";
    std::cout << "result2: " << result2 << "\n";
    std::cout << std::boolalpha;
    std::cout << "val1: " << val1 << "\n";
    std::cout << "val2: " << val2 << "\n";

    return 0;
}
OutputSuccess
Important Notes
Remember: multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).
Logical AND (&&) has higher precedence than logical OR (||).
Use parentheses to make your code clear and avoid mistakes.
Summary
Operator precedence decides which operation runs first in an expression.
Use parentheses to control or clarify the order of operations.
Knowing precedence helps avoid bugs and makes code easier to understand.