What is the effect of typedef'ing a struct to

2019-05-23 18:46发布

This question already has an answer here:

I've seen this code written at the top of an API:

typedef struct SYSTEM SYSTEM;

The type SYSTEM was previously undefined. Does anyone know what this does? What does the compiler think a SYSTEM after this line?

Thanks for the answers! My question is that SYSTEM was not previously defined in the file, so I have no idea what it is. For example, that line will compile by itself, but struct SYSTEM was not defined anywhere.

标签: c++ c struct
2条回答
来,给爷笑一个
2楼-- · 2019-05-23 19:00

It allows you in C to use the name SYSTEM instead of using struct SYSTEM. The typedef creates a synonym SYSTEM to struct SYSTEM.

In your case as struct SYSTEM is not declared, the declaration also declares struct SYSTEM as an incomplete type like in this declaration: struct SYSTEM;.

The complete object type struct SYSTEM can then be declared in another translation unit.

查看更多
【Aperson】
3楼-- · 2019-05-23 19:13

This is really only effective and useful in C.

In C, you have to type struct type, while C++ allows you to omit the struct part of the type and just write type.

typedef struct type type allows you to use type in C without having to use the struct keyword before the struct name.

Some C programmers regard this bad practice though, and prefer to write struct type. Just trying to put that out there.


The reason you're not getting any errors is because that line acts as a forward declaration for the struct SYSTEM that may or may not exist. All the typedef does is tell the compiler that when you say X, you mean Y.

查看更多
登录 后发表回答