here the code below gives me 400 as result but I couldn't quite
understand what is going on here.
struct a and the array have the same name then inside the main
function why sizeof chooses the array one? What is the rule here.
#include <iostream>
int a[100];
struct a
{
int i;
};
int main()
{
std::cout << sizeof(a) << std::endl;
}
"struct a" creates a typename, whereas "int a[100]" creates a variable
name. You can create variables with the same name as existing types, and
these hide the original types (you are not supposed to know and avoid all
those names of existing types in all those included headers).
It isn't a question of whether "a" is a typename or not; only
class or enum types can conflict with other names in this way.
And it has nothing to do with the names in the standard library:
all of the names in the standard library are in namespace std,
and there are more functions than types anyway. The motivation
is simply C compatibility: in C, the name directly following
a struct, union or an enum is called a tag, and is in a separate
symbol table than other names. This works because in C, you
must precede such names with the corresponding elaborated type
specifier. If you look in <sys/stat.h> on a Posix machine, for
example, you'll find:
struct stat { /* ... */ };
int stat( /* ... */ );
A function with the same name as the structure.
One should, of course, avoid using the same names in new C++.
But C++ does have to be able to include the Posix headers (which
were there before there was C++).