typedef enum

W

wongjoekmeu

Hello all,
I was wondering what the differences are between these two things:

1) enum color { RED, BLUE };

and

2) typedef enum { RED, BLUE } color;

Is there a difference anyway ? Why would you prefer one above the
other ?

Thanks for answering.

RR
 
A

asterisc

Hello all,
I was wondering what the differences are between these two things:

1) enum color { RED, BLUE };

and

2) typedef enum { RED, BLUE } color;

Is there a difference anyway ? Why would you prefer one above the
other ?

Thanks for answering.

RR

In C++ there is no difference.
 
R

Rolf Magnus

Hello all,
I was wondering what the differences are between these two things:

1) enum color { RED, BLUE };

This defines an enumerated type called "color".
and

2) typedef enum { RED, BLUE } color;

This defines a nameless enumerated type and gives it the "alias"
name "color".
Is there a difference anyway ? Why would you prefer one above the
other ?

I prefer 1), because it's simpler and shorter. 2) is not needed in C++. It
is used in C, because there, enums have a different namespace. You'd have
to always refer to the type as "enum color" if you use 1), while you can
simply refer to it as "color" when using 2). In C++, you can refer to it
as "color" both ways.
 
J

James Kanze

This defines an enumerated type called "color".
This defines a nameless enumerated type and gives it the
"alias" name "color".

No. There is a special rule in this case (for compatibility
with frequent C use, and support of such use in mixed language
headers) which says that for most intents and purposes, the
"nameless enum type" behaves as if it had the first name in the
typedef.

It's obviously a compatibility hack, and I wouldn't use it in
C++, but it is part of the language. Seeing it, however,
strongly suggests to me that the programmer came from C, and
hasn't yet mastered C++.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top