tags:

views:

1183

answers:

4

If I have something like the following in a header file:

enum Foo
{
   BAR,
   BAZ
};

how do I declare a function that returns an enum of type foo? Can I just do something like the following:

Foo testFunc()
{
    return Foo.BAR;
}

Or do I need to use typedefs or pointers or something?

+3  A: 

I believe that the individual values in the enum are identifiers in their own right, just use:

enum Foo testFunc(){
  return BAR;
}
dmckee
In C, it needs enum Foo; in C++, just Foo would be OK.
Jonathan Leffler
Thanks. Or the type def that Kenny suggests, I suppose.
dmckee
Yes - or the typedef would work, but in C++ that is 'automatic' but in C it must be created manually.
Jonathan Leffler
+1  A: 

I think some compilers may require

typedef enum tagFoo
{
  BAR,
  BAZ,
} Foo;
kenny
C compilers would accept the function with the typedef in place; C++ compilers do not require it.
Jonathan Leffler
A: 
enum Foo
{
   BAR,
   BAZ
};

In C, the return type should have enum before it. And when you use the individual enum values, you don't qualify them in any way.

enum Foo testFunc()
{
    enum Foo temp = BAR;
    temp = BAZ;
    return temp;
}
Brian R. Bondy
+7  A: 

In C++, you could use just Foo.

In C, you must use enum Foo until you provide a typedef for it.

And then, when you refer to BAR, you do not use Foo.BAR but just BAR. All enumerated constants share the same namespace.

Hence (for C):

enum Foo { BAR, BAZ };

enum Foo testFunc()
{
    return BAR;
}
Jonathan Leffler