Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Expressions and operators

Expressions describe computations, while operators specify actions on operands. Learn precedence, associativity, evaluation order, and short-circuit evaluation to read and write C++ expressions correctly.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

a + b * c
(a + b) * c
x = value
x == value
condition && other_condition
condition ? value_if_true : value_if_false

An expression describes a computation: it can produce a value and cause side effects, such as changing a variable. The literal 2, the name a, and the operation a + b are expressions. An operator acts on operands: !a has one operand, a + b has two, and condition ? x : y has three. Operand types affect the available operations and conversions.

Arithmetic operators include +, -, *, /, and %; comparisons include ==, !=, and <. Do not confuse assignment = with comparison ==. For integer operands, / discards the fractional part toward zero, while % computes the remainder. Built-in &&, ||, and ! are logical; &, |, and ^ applied to integers operate on bits.

Precedence determines grouping between different operators: a + b * c means a + (b * c). Associativity determines grouping at the same precedence level: a - b - c means (a - b) - c. Parentheses let you change grouping. This does not establish a general operand evaluation order. Avoid unsequenced modifications of the same variable, such as i++ + i++: they cause undefined behavior.

Built-in && skips its right operand when the left is false, and || skips it when the left is true. This prevents division by zero in the example. The ?: operator evaluates only the selected branch. Overloaded && and || do not provide short-circuit evaluation; overloading itself does not change an operator's precedence or associativity.

The example uses rules available in C++23. The supplied site contains an evolving working draft, not a frozen C++23 publication. The compiler flag selects C++23 mode; it does not attest to the production runtime environment.

Examples

#include <iostream>

int main() {
    const int a = 2;
    const int b = 3;
    const int c = 4;
    const int divisor = 0;

    const int normal = a + b * c;
    const int grouped = (a + b) * c;
    const bool safe = divisor != 0 && normal / divisor > 1;
    const int chosen = safe ? normal : grouped;

    std::cout << normal << ' ' << grouped << ' '
              << std::boolalpha << safe << ' ' << chosen << '\n';
}

Result

14 20 false 20

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources