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 = 14;
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).