Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef with a forward declaration side-effect?

I have the following declaration in a header file:

struct my_struct;
int func(struct my_struct* s);        // Passing struct my_struct*

Without the forward declaration, the compiler would obviously give this error:

error: 'struct my_struct' declared inside parameter list

However, if I replace the forward declaration of my_struct with a typedef, and update the function declaration accordingly, it compiles fine:

typedef struct my_struct my_struct_t;
int func(mystruct_t* s);              // Passing my_struct_t*

Curiously, if I keep the typedef, but use the original declaration my_struct, it also compiles:

typedef struct my_struct my_struct_t;
int func(struct my_struct* s);        // Passing struct my_struct*

Did anybody else notice that? Is that behavior a side-effect?

like image 547
Eitan T Avatar asked Jul 08 '12 13:07

Eitan T


1 Answers

In section 6.2.1, paragraph 7:

Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.

And in 6.7.2.3, paragraph 8:

If a type specifier of the form struct-or-union identifier occurs other than as part of one of the above forms, and no other declaration of the identifier as a tag is visible, then it declares an incomplete structure or union type, and declares the identifier as the tag of that type.

The typedef thus declares an incomplete structure type.

like image 107
Daniel Fischer Avatar answered Sep 26 '22 06:09

Daniel Fischer