User Tools

Site Tools


en:cs:cpp:common:expression

Expression

An expression is a combination of literals, variables, operators and function calls that compute a single value.

Statements produce a single value when they are evaluated.

The process of executing an expression is called evaluation

When evaluating an expression, each of the terms in the expression is evaluated until a single value remains

In C++, expressions and declarations are often confused. Expressions are the building blocks of statements.

int x;
 
int y = { 5 + 8 };

In the example above, int x is an expression and when we add ; at the end, it becomes a declaration. Similarly, in the second line, 5 + 8 is an expression. int y = { 5 + 8 }; is a statement.

Statements cannot be compiled on their own. They must necessarily be part of a statement. Of course, this is easy to solve. If we add ; to the end of any expression, we make an expression statement.

Based on this rule, we can turn any expression into a statement. However, compilers may give a warning if we turn unusable expressions into statements. For example, the following code will compile successfully. However, the calculated value is useless and will be discarded.

(5 + 8);

To help determine how expressions should be evaluated by the compiler and where they can be used;

All expressions in C++ have two properties: a type and a value category.

The type of the expression is the type that remains after the expression has been evaluated. See the code below as an example.

auto v1 { 12 / 4 }; // int / int => The type of the expression is int since int returns int.
auto v2 { 12.0 / 4 }; // double / int => The type of the expression is double since it returns a double result.

Expressions value categories is a little more complicated than the type. You can take a look at the related page.


Taken from UCH Viki. https://wiki.ulascemh.com/doku.php?id=en:cs:cpp:common:expression

en/cs/cpp/common/expression.txt · Last modified: 2025/05/02 22:32 by ulascemh