What is the rationale behind typedef vs struct/union/enum, couldn't there be only one namespace?

倾然丶 夕夏残阳落幕 提交于 2019-12-05 07:03:46

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;

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

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

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.

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.

Well, other languages also usually support namespaces. C doesn't.

It probably isn't the reason, but it makes sense to have at least this natural namespace.

Interesting question! Here are my thoughts.

When C was created, little abstraction existed over assembly language. There was FORTRAN, B, and others, but when C came to be it was arguably the highest level language in existence. It's goal was to provide functionality and syntax powerful enough to create and maintain an operating system, and it succeed remarkably.

Think that, at the time, porting a system to a new platform meant rewriting and adapting components to the platform's assembly language. With the release of C, it eventually came down to porting the C compiler, and recompiling existent code.

It was probably an asset back then that the very syntax of the language forced you to differentiate between types that could fit in a register, and types that couldn't.

Language syntax has evolved a lot since then, and most of the things we're used to see in modern languages are missing in C. User-defined namespaces is only one of them, and I don't think the concept of "syntax sugar" even existed back then. Or rather, C was the peak of syntax sugar.

We're surrounded with things like this. I mean, take a look at your keyboard: why do we ave a PAUSE/BREAK key? I don't think I've pressed that key for years.

It's inheritance from a time in which it made sense.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!