The given C code
#include <stdio.h>
int x = 14;
size_t check()
{
struct x {};
return sizeof(x); // which x
}
int main()
{
printf("%zu",check());
return 0;
}
gives 4 as output in C on my 32 bit implementation whereas in C++ the code
#include <iostream>
int x = 1开发者_如何学编程4;
size_t check()
{
struct x {};
return sizeof(x); // which x
}
int main()
{
std::cout<< check();
return 0;
}
outputs 1. Why such difference?
In C++ class declaration struct x {};
introduces the name x
into the scope of check
and hides x
(previously declared as int
at file scope). You get 1 as the output because size of empty class cannot be zero in C++.
In C, an inner scope declaration of a struct tag name never hides the name of an object or function in an outer scope.You need to use the tag name struct
to refer to the typename x
(struct). However you can't have an empty struct in C as it violates the syntactical constraints on struct(however gcc supports it as an extension).
The C code is giving you the size of the global variable 'x', whereas the C++ code is giving the size of the empty struct. To get the size of the struct x in the C code, use sizeof(struct x)
In C, struct tags live in a separate name space, and you have to use the struct keyword to access names in there. This is the reason that the "typedef struct {} x" idiom is so popular in C--it allows you to essentially promote struct names to the global namespace.
In C++, by contrast, structs (and all other names) live in the namespace surrounding the declaration, rather than a separate struct tag namespace as in C.
As Saurabh said, use sizeof(struct x) in C, or use the typedef struct {} x
trick to get sizeof(x) to work as in C++.
As an added bonus, the C++ program outputs 1 because concrete class objects must have nonzero size (so that different objects must have different addresses), so the compiler has padded the struct with an anonymous char value.
精彩评论