tags:

views:

139

answers:

3

Hi folks:

I have a problem with the typedef keywords in C language.

In my program, I use the following codes:

typedef int* a[10];

int main(){
 int a[10];
} 

they work well. But why there are no conflicts between a variable and a type sharing the same name a?

Regards.

+5  A: 

The C standard says (Section 6.2.1 - Scopes of identifiers):

An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter. The same identifier can denote different entities at different points in the program.

K&R2 say (A.11.1 - Lexical Scope)

Identifiers fall into several name spaces that do not interfere with one another; the same identifier may be used for different purposes, even in the same scope, if the uses are in different name spaces. These classes are: objects, functions, typedef names, and enum constants; labels; tags of structures or unions, and enumerations; and members of each structure or union individually.

I must admit this confuses me. Reading the second quote it appears that variable names and typedef-ed types should clash.

Eli Bendersky
But I am still not very clear how can "a" denoting different entities coexists in the preceeding codes. Could you give me further explanation, please? Thanks.
Summer_More_More_Tea
@Neil: I read the punctuation differently. Seems like objects, functions, typedef names and enum constants are one class. Next (after a semicolon) labels, next tags, etc.
Eli Bendersky
+6  A: 

See msdn C language reference:

Typedef names share the name space with ordinary identifiers (see Name Spaces for more information). Therefore, a program can have a typedef name and a local-scope identifier by the same name.

tanascius
Curious quote. Reading it quickly it feels like an oxymoron. If they share a namespace, how could they have the same name? Is this because of the *local-scope*?
Eli Bendersky
Hmm... the "Name Spaces" link you point to says: "Typedef names cannot be used as identifiers in the same scope. "
Eli Bendersky
@Eli: `{int x; {float x;} }`
sbi
@sbi: the compiler forgives even if `int a[10]` is declared in the global scope together with the typedef
Eli Bendersky
@Eli Bendersky: GCC 4.4.1 doesn't show much forgiveness and refuses to compile the source code if you put the variable declaration into the same scope as the typedef (i.e. moving the variable declaration to global scope or the typedef into main())
Dirk D
+3  A: 

Variables and typedefs occupy the same namespace, and can not share names with other identifiers in exactly the same scope.

However your second a is inside main, and scope rules apply: the second a overrides the first.

You can do the same thing with just plain variables:

int a;

int main() {
    int a;
}

You'll notice that if you move the variable declaration outside main, the program won't compile.

Chris Burt-Brown