Is the expression "C ++ declaration and initialization" an expression?

The language standard says:

[Note: paragraph 5 defines the syntax, evaluation order, and meaning of expressions .58 An expression is a sequence of operators and operands that define a calculation. Expression can lead to and can cause side effects. - final note]

eg. I have the code below:

int i=1; A obj; 

So, do both statements above, read the "expression"?

Some people on stackoverflow say "int i = 1;" not an expression. This is pretty weird for me.

(1) Initialization is a kind of "calculation", right? Therefore, should it be regarded as an “expression”?

(2) A obj; // calls ctor. Ctor is a kind of calculation, so should it be considered as an "expression"?

+5
source share
1 answer

This non-normative note in the standard is intended to motivate the concept of expression, but is not an actual definition. The definition of an expression is given in the grammar of the language, which is given in the rest of paragraph 5. The expressions are constructed from certain terminals, such as literals, variable names, and function names, which are combined using operators such as arithmetic and relational operators.

Declarations and expressions are various syntactic entities, therefore an ad found inside a C ++ program is never an expression, and vice versa. The difference is pretty easy to see at a glance: if she announces something, this is an announcement.

 1; // expression statement int i = 1; // declaration statement that declares `i` A(i, 42); // expression statement that creates an A object A a(i); // declaration statement that declares an A object (named a) 

An ad may evaluate expressions, but a declaration is not an expression. You rightly point out that declaring an object of type class can cause a constructor call. However, this is a syntax declaration, not an expression.

However, there is another point in which the declaration is an expression. Namely, the rules on the sequence of evaluations in expressions also apply to declarations. For example, there is a rule that the side effect of incrementing a postfix on an int occurs at some point before the end of the full expression.

 f(i++) + g(); // i may be incremented before or after g() is called... h(); // but definitely before h() is called. 

For the purpose of such rules, declaring and initializing one variable is also considered a complete expression. In the case of a class type variable, a constructor call is part of this expression.

 int i = 1; // this declaration evaluates a full-expression // whose effect is to initialize `i` to 1 int j = f(i++) + g(), k = h(); // two separate full-expressions; // i is incremented before h() is called 

When reading the standard, you need to consider the context to understand what the term “expression” means.

+6
source

All Articles