md5
md5

Reputation: 23699

Is a declaration an expression?

I'd like to know if, in the following declaration, p is an lvalue, i.e. is p an expression in this declaration ? (if the answer is "yes", it's an lvalue because p changes the value of the object located at &p with the value &n).

unsigned char *p = &n;

Upvotes: 1

Views: 220

Answers (3)

Jens Gustedt
Jens Gustedt

Reputation: 78903

Short answer to your question: no, a declaration is not an expression. Declarations may contain expressions to determine the type, but that's it, and the initializer expression is an expression, too.

Seen as that your question about lvalue makes no sense. Since it is not an expresssion, it doesn't have a value.

Upvotes: 1

MvG
MvG

Reputation: 60868

Judging from the grammar part of Stroustrups C++ book, a declaration statement is not an expression statement. I guess that applies to classic C as well. So while your initializer is an expression, your declaration as a whole is not an expression. Neither is the thing with the equals sign really an assignment in the strict sense; instead it is an initialization, which is slightly different. For this same reason, p is not really an expression, even if assignments and initializations share many common rules.

Upvotes: 2

ouah
ouah

Reputation: 145829

C says (emphasis mine) for initialization of a scalar:

(C99, 6.7.8p11) "The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type."

and the constraints of the assignment operators says the left operand must be a (modifiable) lvalue.

And for the terminology, a declaration is not an expression nor a statement but the initializer can be an expression.

Upvotes: 4

Related Questions