The Question :
- In programming , assignment statement is an expression , but how about initialization?Is it an expression??
-
the parentheses of a
whileloop should contain an expression , so i try to put an initialization into it , and the compiler prompt me an error , this shows initialization is not an expression. -
To further prove it , i try the
forloop , and i do thisfor(int num = 3 ; num2 = 4 ; num3 = 5).Surprisingly the compiler give me errors again. -
So if an initialization is not an expression , what kind of statement it is??
Thanks for spending time reading my question
In both C and C++, assignment is an expression. E.g.
a = 5is an assignment-expression.In both C and C++ you can use any expression followed by a semi-colon where statement is required – such as the body of a function. This type of statement is an expression-statement. (Technially, you can leave out the expression entirely.
;is a degenerate expression-statement.)You can only use a declaration where a declaration is expected, not everywhere where you can use an expression.
The following is not an expression or an expression-statement, it is a declaration. (Technically, in C++, it can form a declaration-statement when used where a statement is expected, in C it is just a declaration.) Note that there is no assignment-expression sub-part to this declaration,
= 3is an initializer for the declared entitynum.These two common uses of
=(initialization and assignment) are sometimes confused. Where=is being used to initialize the entity being declared in a declaration, it is initialization, where it is being used to change the value of an already declared entity, it is assignment.Here is where C and C++ differ: in C, the parenthesised entity immediately following the
whilekeyword must be an expression so something likewhile (int num = 0) { /* ... */ }is not valid.In C++ the entity can be a condition, which allows for a simple declaration with an initializer as well as a simple expression, as in C. In C++, where the condition is in the form of a declaration, the declared entity is initialized on each iteration and implicitly converted to
boolto determine whether to execute the loop body.The
forloop is special in both languages. In both languages the first part of the parenthesized list following theforkeyword can effectively be either a declaration or an expression-statement.