If I have something like the following in a header file, how do I declare a function that returns an enum of type Foo? functions can return enumeration constants in c
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?
In C, you don’t need to use any typedefs or pointers to return an enumeration constant from a function. Your code is almost correct, but you should omit the enum name when returning the enumeration constant. Here’s the correct way to declare the function and return the enum value:
enum Foo
{
BAR,
BAZ
};enum Foo testFunc()
{
return BAR;
}
As you can see, you simply return the enumeration constant BAR
directly from the function testFunc()
. There’s no need to write Foo.BAR
as you would do in some other programming languages like C# or Java. In C, the enum constants are in the global scope, so you can use them directly without prefixing them with the enum name.
If you are using C99 or later, you can also omit the enum
keyword in the return type:
enum Foo testFunc()
{
return BAR;
}
Alternatively, you can use a typedef
to create a shorter alias for the enum type, but it’s not necessary for returning enum constants from functions:
typedef enum Foo Foo;
enum Foo
{
BAR,
BAZ
};Foo testFunc()
{
return BAR;
}
Both versions of the testFunc()
function will work fine in C, and you can choose whichever style you prefer.