Returning an enum from a function in C?
Asked Answered
G

4

37

If I have something like the following in a header file, how do I declare a function that returns an enum of type Foo?

enum Foo
{
   BAR,
   BAZ
};

Can I just do something like the following?

Foo testFunc()
{
    return Foo.BAR;
}

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

Gat answered 13/4, 2009 at 0:24 Comment(0)
L
70

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 enumeration constants share the same namespace (the “ordinary identifiers” namespace, used by functions, variables, etc).

Hence (for C):

enum Foo { BAR, BAZ };

enum Foo testFunc(void)
{
    return BAR;
}

Or, with a typedef:

typedef enum Foo { BAR, BAZ } Foo;

Foo testFunc(void)
{
    return BAR;
}
Liz answered 13/4, 2009 at 0:36 Comment(1)
yet another reason why people dislike C++Dyann
B
5

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

enum Foo testFunc(){
  return BAR;
}
Bogey answered 13/4, 2009 at 0:27 Comment(3)
In C, it needs enum Foo; in C++, just Foo would be OK.Liz
Thanks. Or the type def that Kenny suggests, I suppose.Bogey
Yes - or the typedef would work, but in C++ that is 'automatic' but in C it must be created manually.Liz
C
2

I think some compilers may require

typedef enum tagFoo
{
  BAR,
  BAZ,
} Foo;
Courtly answered 13/4, 2009 at 0:29 Comment(1)
C compilers would accept the function with the typedef in place; C++ compilers do not require it.Liz
H
2
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;
}
Hyacinthe answered 13/4, 2009 at 0:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.