简体   繁体   中英

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:

  1. It brings to the fore the difference between reference and referent
  2. It's how C enables separation in time of the attachment between reference and referent.

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:

  • for an object, causes storage to be reserved for that object;
  • for a function, includes the function body;
  • for an enumeration constant, is the (only) declaration of the identifier;
  • for a typedef name, is the first (or only) declaration of the identifier.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM