Reputation: 33
When declaring a variable or pointer, the compiler assumes the variable or pointer itself is already declared when being assigned as a value during declaration.
I have tried both gcc and clang and they compile the "faulty" code without complaining.
CASE 1: This will not compile since "a" is not declared:
void main()
{
int b=sizeof(a);
}
CASE 2: This compiles without a problem:
void main()
{
int a=sizeof(a);
}
Shouldn't the compiler generate the "a is undeclared" error instead, just like in case 1?
Upvotes: 2
Views: 69
Reputation: 170044
Shouldn't the compiler generate the "a is undeclared" error instead, just like in case 1?
Why? It just saw you declare a
.
int a = sizeof(a);
// ^--- here it is, before its first use
The declaration of a variable begins after its declarator is seen, right before its (optional) initializer. So you can even write the truly faulty
int a = a;
Note however that in your case there is nothing faulty being done. The result of sizeof
depends only on the type of a
, and the type is known. This is a well defined initializtion (with a conversion from size_t
to int
, but not one to be worried about).
Upvotes: 4
Reputation: 10872
sizeof
is not a function depending on the value of a
; it is a builtin that is evaluated at compile time, so it becomes equivalent to
int a = 4;
Upvotes: 4