Repeated typedefs – invalid in C but valid in C++?

Why does this compile in C++?

Because the C++ Standard explicitly says so.

Reference:

C++03 Standard 7.1.3 typedef specifier

§7.1.3.2:

In a given non-class scope, a typedef specifier can be used to redefine the name of any type declared in that scope to refer to the type to which it already refers.

[Example:
typedef struct s { /* … */ } s;
typedef int I;
typedef int I;
typedef I I;
—end example]

Why does this fail to compile in C?

typedef names have no linkage and C99 standard disallows identifiers with no linkage specification to have more than one declaration with the same scope and in the same name space.

Reference:

C99 Standard: §6.2.2 Linkages of identifiers

§6.2.2/6 states:

The following identifiers have no linkage: an identifier declared to be anything other than
an object or a function; an identifier declared to be a function parameter;
a block scope
identifier for an object declared without the storage-class specifierextern.

Further §6.7/3 states:

If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except for tags as specified in 6.7.2.3.

Leave a Comment