Reputation: 485
code:
int main()
{
extern int a;
int b;
cout<<sizeof(a)<<endl;
cout<<sizeof(b)<<endl;
}
output:
4
4
If we just declare a variable, it shouldn't allocate memory for that variable(?). So how would the compiler not giving an error for
cout<<sizeof(a)<<endl;
or why the program is not getting crashed?
Upvotes: 0
Views: 177
Reputation: 24269
sizeof() is not a function, it is a language keyword, that resolves to a compile time constant.
So - you are not accessing or using "a", rather you are asking the compiler a question about one of the pieces of information you provided it about "a".
cout << sizeof( a ) << endl:
is actually
cout << sizeof decltype(a) << endl;
is actually
cout << sizeof int << endl;
is actually
cout << 4 << endl;
You can verify this by looking at the assembly output. Under Linux, with GCC or Clang,
c++ -Wall -o test.S -S test.cpp
will generate the assembly file for you to inspect.
Upvotes: 2
Reputation: 19731
With extern int a
you are just telling the compiler that there is (supposed to be) a variable named a
of type int
somewhere. However the only thing you do is to apply sizeof
to it. Now the compiler doesn't need to access a
to know its size: Since you told the compiler that a
is of type int
, it already knows its size: All int
s are of the same size.
As of why the compiler does not give an error: A missing definition for an extern
entity only gives an error if that entity is actually used. Since sizeof
doesn't use it, but only tells you the size, you don't get a compiler error.
Upvotes: 1
Reputation: 546153
sizeof
is resolved at compile time. All the compiler needs is a declaration with a complete type – it does not need to allocate storage for the object.
Since the sizeof
expression is resolved at compile time, there’s consequently also no way check whether the object is actually defined in another compilation unit. If we wanted this check we couldn’t evaluate sizeof
at compile time (we’d have to defer it to link time), and there’s simply no good reason for this delay.
Upvotes: 3
Reputation: 727087
The sizeof
does not need to evaluate the expression that you pass to it, only its type. External definition extern int a
is sufficient to figure out the type, so sizeof
succeeds.
Moreover, since the expression inside sizeof
does not get evaluated, the program links without an error.
Upvotes: 4
Reputation: 29985
The compiler knows that int
has a size of 4, and there's nothing that could ever give an int
another size after compilation. Because of that, sizeof(a)
becomes sizeof(int)
which becomes 4
.
Upvotes: 2
Reputation: 12042
Because it's getting the size of the type of the variable and not of the actual memory used (that should be the same).
int main () {
int a = 2;
std::cout << sizeof ((char) a) << std::endl; // Outputs 1
return 0;
}
Upvotes: 1