开发者

typedef struct and enum, why? [duplicate]

开发者 https://www.devze.com 2023-02-14 04:05 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Purpose of struct, typedef struct, in C++
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Purpose of struct, typedef struct, in C++

typedef struct vs struct definitions

In code that I am mai开发者_JAVA技巧ntaining I often see the following:

typedef enum { blah, blah } Foo;
typedef struct { blah blah } Bar;

Instead of:

enum Foo { blah, blah };
struct Bar { blah blah };

I always use the latter, and this is the first time I am seeing the former. So the question is why would one use one style over the other. Any benefits? Also are they functionally identical? I believe they are but am not 100% sure.


In C++ this doesn't matter.

In C, structs, enums, and unions were in a different "namespace", meaning that their names could conflict with variable names. If you say

struct S { };

So you could say something like

struct S S;

and that would mean that struct S is the data type, and S is the variable name. You couldn't say

S myStruct;

in C if S was a struct (and not a type name), so people just used typedef to avoid saying struct all the time.


They are for C compatability. A normal

  struct Bar { blah, blah };

doesn't work the same with C;

0

精彩评论

暂无评论...
验证码 换一张
取 消