什么是背后的typedef VS结构/联合/枚举的理由,不能有只有一个命名空间? [英] What is the rationale behind typedef vs struct/union/enum, couldn't there be only one namespace?

查看:105
本文介绍了什么是背后的typedef VS结构/联合/枚举的理由,不能有只有一个命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,如果我宣布一个结构/联合/枚举:

In C if I declare a struct/union/enum:

struct Foo { int i ... }

当我想用我的结构我需要指定标记:

when I want to use my structure I need to specify the tag:

struct Foo foo;

要失去这个要求,我一直在使用的typedef别名我的结构:

To loose this requirement, I have to alias my structure using typedef:

typedef struct Foo Foo;

为什么不拥有各类/结构/不管在同一个命名默认?什么是需要的声明标记每个变量声明(除非typdefe'd)的决定背后的理由?

Why not have all types/structs/whatever in the same "namespace" by default? What is the rationale behind the decision of requiring the declaration tag at each variable declaration (unless typdefe'd) ???

许多其他语言不作这种区分,而且似乎它只是使复杂恕我直言额外级别的。

Many other languages do not make this distinction, and it seems that it's only bringing an extra level of complexity IMHO.

推荐答案

结构/记录是一个非常早期的pre-C除了B,刚过丹尼斯里奇增加了一个基本的类型化的结构。我认为,原始的结构语法没有标记所有,为你做的每一个变量匿名结构

Structures/records were a very early pre-C addition to B, just after Dennis Ritchie added a the basic 'typed' structure. I believe that the original struct syntax did not have a tag at all, for every variable you made an anonymous struct:

struct {
    int  i;
    char a[5];
} s;

后来,添加标签,使结构布局的重用,但它并没有真正被视为真正的类型。另外,删除结构 / 联盟将使解析不可能的:

Later, the tag was added to enable reuse of structure layout, but it wasn't really regarded as real 'type'. Also, removing the struct/union would make parsing impossible:

/* is Foo a union or a struct? */
Foo { int i; double x; };
Foo s;

或破坏的声明语法模仿前pression语法的范例,它如此重要到C

or break the 'declaration syntax mimics expression syntax' paradigm that is so fundamental to C.

我怀疑的typedef 已晚得多加,可能几年后的C'生'了。

I suspect that typedef was added much later, possible a few years after the 'birth' of C.

参数C是当时最高级别的语言。似乎不如此。大陵68 predates并有记录为适当的类型。这同样适用于帕斯卡。

The argument "C was the highest level language at the time." does not seem true. Algol-68 predates it and has records as proper types. The same holds for Pascal.

如果你想知道更多关于C的历史,你会发现里奇的的c语言的发展的一个有趣的阅读。

If you like to know more about the history of C you might find Ritchie's "The Development of the C Language" an interesting read.

这篇关于什么是背后的typedef VS结构/联合/枚举的理由,不能有只有一个命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆