Sorry, If this type of question already asked on SO, but this is new for me when I tried following simple program.
#include <stdio.h>
void foo()
{
puts("foo() is invoked");
}
struct foo
{
int a;
};
int main()
{
struct foo f={3};
printf("%d\n",f.a);
foo();
}
Shouldn't we get an error? How it is possible to use same identifier for both function & struct in C & C++? What the C & C++ standard says about this?
Tag names (for structs, unions, and enums) occupy a different name space from identifiers (function, object, and typedef names). Tag names are disambiguated by the presence of the
struct
,union
, orenum
keywords1.Note that struct and union member names occupy yet another namespace and are disambiguated in expressions by the use of the
.
or->
component selection operators, so the following code is legal (if a really bad idea):The type name
struct foo
is disambiguated by the presence of thestruct
keyword, and the member namefoo.foo
is disambiguated by the presence of the.
operator.Here are the things you cannot do:
1. I'm assuming this is also the case for the
class
keyword in C++, but I don't have that reference handy.