Why is a typedef declaration not called a typedef definition?
I see occasional questions such as "what's the difference between a declaration and a definition":
What is the difference between a definition and a declaration? The distinction is important and intellectually it achieves two important things:
So why is a C typedef
declaration not called a typedef
definition?
Firstly, it's obviously a definition. It defines an alias. The new name is to be taken as referring to the existing thing. But it certainly binds the reference to a specific referent and is without doubt a defining statement.
Secondly, wouldn't it be called a typedec
if it were a declaration?
Thirdly, wouldn't it avoid all those confusing questions people ask when they try and make a forward declaration using a typedef?
A typedef
declaration is a definition.
N1570 6.7p5:
A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:
In C99, the last two bullet points were combined; C11 introduced the ability to declare the same typedef
twice.
Note that only objects, functions, enumeration constants, and typedef names can have definitions. One might argue that given:
enum foo { zero, one};
it doesn't make much sense to consider this to be a definition of zero
and one
, but not of foo
or enum foo
. On the other hand, an enum
, struct
, or union
declaration, though it creates a type that didn't previously exist, doesn't define an identifier that is that type's name -- and for struct
s and union
, the tag name can be used (as an incomplete type) even before the type has been defined. Definitions define identifiers, not (necessarily) the entities to which they refer.
As for why it's not called a "definition" in the subsection that defines it, it's part of section 6.7 "Declarations", which covers all kinds of declarations (some of which are also definitions). The term definition is defined in the introductory part of 6.7.
As for the name typedef
, it's caused a fair amount of confusion over the years since it doesn't really define a type. Perhaps typename
would have been a better choice, or even typealias
. But since it does define the identifier, typedef
isn't entirely misleading.
上一篇: 将当前更改放入新的Git分支中