Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass ENUM as function argument in C

Tags:

c

function

enums

I have an enum declared as;

typedef enum  {    NORMAL = 0,               EXTENDED                }CyclicPrefixType_t;  CyclicPrefixType_t cpType;   

I need a function that takes this as an argument :

fun (CyclicPrefixType_t cpType) ;   

func declaration is :

void fun(CyclicPrefixType_t cpType); 

Please help. I don't think it is correct.

Thanks

like image 367
user437777 Avatar asked Jan 11 '11 05:01

user437777


People also ask

How do you pass an enum in a method argument?

Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum. Show activity on this post. Show activity on this post. First change the method parameter Enum supportedPermissions to SupportedPermissions supportedPermissions .

How do you use enums as a function?

enum State {Working = 1, Failed = 0}; The keyword 'enum' is used to declare new enumeration types in C and C++. Following is an example of enum declaration. // The name of enumeration is "flag" and the constant // are the values of the flag.

How do I pass enum as reference?

You can use the operator & ( bitwise and ) and ( | bitwise or ) and use each bit as a bool. Remind that a enum behaves as a int. For example, if the user has pressed the keys W and S. Show activity on this post.

Can you cast an enum in C?

Yes. In C enum types are just int s under the covers. Typecast them to whatever you want. enums are not always ints in C.


2 Answers

That's pretty much exactly how you do it:

#include <stdio.h>  typedef enum {     NORMAL = 31414,     EXTENDED } CyclicPrefixType_t;  void func (CyclicPrefixType_t x) {     printf ("%d\n", x); }  int main (void) {     CyclicPrefixType_t cpType = EXTENDED;     func (cpType);     return 0; } 

This outputs the value of EXTENDED (31415 in this case) as expected.

like image 62
paxdiablo Avatar answered Sep 19 '22 06:09

paxdiablo


The following also works, FWIW (which confuses slightly...)

#include <stdio.h>  enum CyclicPrefixType_t {     NORMAL = 31414,     EXTENDED };  void func (enum CyclicPrefixType_t x) {     printf ("%d\n", x); }  int main (void) {     enum CyclicPrefixType_t cpType = EXTENDED;     func (cpType);     return 0; } 

Apparently it's a legacy C thing.

like image 34
rogerdpack Avatar answered Sep 21 '22 06:09

rogerdpack