Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an enum from a function in C?

Tags:

c

function

enums

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?

like image 476
Paul Wicks Avatar asked Apr 13 '09 00:04

Paul Wicks


People also ask

Can C function return enum?

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).

Can enum be a return type or function?

enum is a data type, not a function.

What is typedef enum in C?

A typedef is a mechanism for declaring an alternative name for a type. An enumerated type is an integer type with an associated set of symbolic constants representing the valid values of that type.

Which method returns enum class?

The valueOf() method takes a string and returns an enum constant having the same string name.


2 Answers

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; } 
like image 115
Jonathan Leffler Avatar answered Sep 17 '22 08:09

Jonathan Leffler


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

enum Foo testFunc(){   return BAR; } 
like image 21
dmckee --- ex-moderator kitten Avatar answered Sep 21 '22 08:09

dmckee --- ex-moderator kitten