Expressions
An expression is a sequence of operators and their operands, that specifies a computation.
Expression evaluation may produce a result (e.g., evaluation of 2 + 2 produces the result 4) and may generate side-effects (e.g. evaluation of std::printf("%d", 4) prints the character '4' on the standard output).
Each C++ expression is characterized by two independent properties: A type and a value category.
Contents |
[edit] General
- value categories (lvalue, rvalue, glvalue, prvalue, xvalue(since C++11)) classify expressions by their values
- order of evaluation of arguments and subexpressions specify the order in which intermediate results are obtained
[edit] Operators
| Common operators | ||||||
|---|---|---|---|---|---|---|
| assignment | increment decrement |
arithmetic | logical | comparison | member access |
other |
|
a = b |
++a |
+a |
!a |
a == b |
a[...] |
function call a(...) |
| comma a, b | ||||||
| conditional a ? b : c | ||||||
| Special operators | ||||||
|
static_cast converts one type to another related type | ||||||
- operator precedence defines the order in which operators are bound to their arguments
- alternative representations are alternative spellings for some operators
- operator overloading makes it possible to specify the behavior of the operators with user-defined classes.
[edit] Conversions
- standard conversions implicit conversions from one type to another
-
const_castconversion -
static_castconversion -
dynamic_castconversion -
reinterpret_castconversion - explicit cast conversion using C-style cast notation and function-style notation
- user-defined conversion makes it possible to specify conversion from user-defined classes
[edit] Memory allocation
- new expression allocates memory dynamically
- delete expression deallocates memory dynamically
[edit] Other
- constant expressions can be evaluated at compile time and used in compile-time context (template arguments, array sizes, etc)
-
sizeof -
alignof -
typeid - throw-expression
[edit] Primary expressions
The operands of any operator may be other expressions or primary expressions (e.g. in 1 + 2 * 3, the operands of operator+ are the subexpression 2 * 3 and the primary expression 1).
Primary expressions are any of the following:
-
this - literals (e.g. 2 or "Hello, world")
- identifier expressions, including
- suitably declared unqualified identifiers (e.g. n or cout),
- suitably declared qualified identifiers (e.g. std::string::npos), and
- identifiers to be declared in declarators
| (since C++26) |
| (since C++11) | |
| (since C++17) | |
| (since C++20) |
Any expression in parentheses is also classified as a primary expression: this guarantees that the parentheses have higher precedence than any operator. Parentheses preserve value, type, and value category.