Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typedef struct and enum, why? [duplicate]

Tags:

c++

enums

struct

Possible Duplicates:
Purpose of struct, typedef struct, in C++
typedef struct vs struct definitions

In code that I am maintaining 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.

like image 518
anio Avatar asked Feb 28 '11 20:02

anio


People also ask

What is difference between struct and typedef struct?

Basically struct is used to define a structure. But when we want to use it we have to use the struct keyword in C. If we use the typedef keyword, then a new name, we can use the struct by that name, without writing the struct keyword.

How does enum is different from typedef in C?

There are two different things going on there: a typedef and an enumerated type (an "enum"). A typedef is a mechanism for declaring an alternative name for a type. An enumerated type is an integer type with an associated set of symbolic constants representing the valid values of that type.

Can we use typedef with enum in C?

An introduction to C Enumerated TypesUsing the typedef and enum keywords we can define a type that can have either one value or another. It's one of the most important uses of the typedef keyword. This is the syntax of an enumerated type: typedef enum { //...

Should you typedef structs?

PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs. Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.


2 Answers

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.

like image 162
user541686 Avatar answered Sep 28 '22 03:09

user541686


They are for C compatability. A normal

  struct Bar { blah, blah };

doesn't work the same with C;

like image 43
Nick Banks Avatar answered Sep 28 '22 02:09

Nick Banks