Learning Hub Search Ctrl K

Legacy C++ › 1. Getting Started

Operators and Expressions

Arithmetic, logical, bitwise operators, precedence and evaluation order.

beginner #operators#precedence#bitwise#evaluation-order

Explanation

Operators group into: arithmetic (+ - * / %), comparison (== != < > <= >=), logical (&& || !), bitwise (& | ^ ~ << >>), assignment (= += -= ...), increment/decrement (++ --), and the conditional ?:.

Key rules:

  • && and || short-circuit: the right side is evaluated only if needed.
  • Precedence decides grouping, but not the order in which operands are evaluated. f() + g() may call either first.
  • Prefix ++i returns the new value; postfix i++ returns a copy of the old one.
  • Modifying a variable twice between sequence points (i = i++ + ++i) is undefined behavior.

Example

#include <iostream>

bool check(const char* name, bool result) {
    std::cout << "evaluating " << name << "\n";
    return result;
}

int main() {
    // short-circuit: check("B") is never called
    if (check("A", false) && check("B", true)) { }

    unsigned flags = 0;
    const unsigned READ = 1u << 0, WRITE = 1u << 1, EXEC = 1u << 2;
    flags |= READ | WRITE;        // set bits
    flags &= ~WRITE;              // clear a bit
    flags ^= EXEC;                // toggle a bit
    std::cout << "flags = " << flags << "\n";   // 5 (READ | EXEC)
    std::cout << ((flags & EXEC) ? "can exec" : "no exec") << "\n";

    int x = 10;
    int y = x++;                  // y == 10, x == 11
    int z = ++x;                  // z == 12, x == 12
    std::cout << y << " " << z << "\n";
    return 0;
}

Common pitfalls

  • if (a = b) assigns instead of comparing. Compilers warn; heed the warning.
  • & vs && and | vs || look alike but differ: one is bitwise, the other logical (with short-circuit).
  • a & b == c parses as a & (b == c) because == binds tighter than &. Parenthesize bit tests.
  • % with negative operands has implementation-defined sign in C++03.
  • Right-shifting a negative signed value is implementation-defined.

Legacy vs modern

C++17 adds defined evaluation order for some operators (e.g. a << b << c, assignments). The undefined cases like i = i++ + ++i remain best avoided.

Exercises

1. What are a and b after int a = 5; int b = a++ * 2;?

b == 10, a == 6: the old value is used in the multiplication.

2. Write an expression that tests whether bit 3 of n is set.

(n & (1u << 3)) != 0