2

Possible Duplicate:
Is the typedef-name optional in a typedef declaration?

I'm on Visual Studio 2008 and I saw this:

typedef enum testfoo
{
    enum1,
    enum2,
    enum3
};

Normally the C-style way of using typedef this way requires one additional piece (the name):

typedef enum testfoo
{
    enum1,
    enum2,
    enum3
} testfoo_name;

What is the former example doing? Strangely it compiles, but not sure what it's actually defining.

Community
  • 1
  • 1
void.pointer
  • 24,859
  • 31
  • 132
  • 243

2 Answers2

0

There is a difference. The second creates an alias for the enum but the first doesn't. The typedef in the first example doesn't actually do anything. This gives me a warning in GCC so I suspect you can take it out.

In C, it's common to typedef structs and enums so as to avoid instantiating with the struct or enum name. For instance:

struct A {};

struct A a;

To shorten this, a typedef does the trick:

typedef struct {} A;

This is no longer necessary in C++ so I'm deriving my assumption of his misconception with this concept. Or maybe the author forgot to give it a name...

The same thing occurs when using classes or structs:

typedef struct A {}; // simply a class-declaration, generates a warning
David G
  • 94,763
  • 41
  • 167
  • 253
  • @CarlNorum: If you're going to create a typedef (which isn't really necessary even in C), you might as well use the same identifier for the typedef name and the tag: `typedef enum testfoo { enum1, enum2, enum 3 } testfoo;` -- which the code in the question didn't do. In C, this lets you refer to the type either as `enum testfoo` or as `testfoo`. In C++ it does the same thing, except that it happens anyway even without the `typedef`. – Keith Thompson Jan 04 '13 at 00:22
  • @Keith - my comment is in reference to a previous version of this answer. It doesn't really make sense anymore - I'll delete it. – Carl Norum Jan 04 '13 at 00:33
0

The first example is just a useless typedef. I believe it's syntactically legal, but it doesn't provide a name for the type definition, so it's equivalent to:

enum testfoo { enum1, enum2, enum3 );

In C, this creates a type with the name enum testfoo; it's common (but not necessary) to use a typedef to allow the type to be referred to as just testfoo.

In C++, the type can be referred to either as enum testfoo or as testfoo, even without the typedef.

I suspect someone was confused about the rules, saw that the type can be referred to (in C++) as testfoo, and incorrectly assumed that this was because of the typedef.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631