enum types as function arguments

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
pneumatic
 
Posts: 186
Joined: Sun Jul 26, 2009 3:59 pm

enum types as function arguments

Post by pneumatic »

My C is really rusty, but it seems like this should work:

Code: Select all

typdef enum Foo_t { bar, baz, quux };

Foo_t foo;

void set_foo(Foo_t arg) {
  foo = arg;
}
But it errors on the function saying that Foo_t isn't defined in this scope (but takes the declaration of foo fine.). I've tried with the typedef and without, and with a separate typedef like so:

Code: Select all

enum Foo_enum {...};

typedef Foo_t Foo_enum;

and nothing seems to work. Is there something fundamental I'm missing?

User avatar
adafruit_support_mike
 
Posts: 67454
Joined: Thu Feb 11, 2010 2:51 pm

Re: enum types as function arguments

Post by adafruit_support_mike »

Your syntax is slightly off, but the compiler is also being obtuse.

The type name goes at the end of the typdef expression:

Code: Select all

typedef enum { 
    bar, baz, quux 
} Foo_t;
and this compiles just fine from the command line:

Code: Select all

typedef enum { 
    bar, baz, quux 
} Foo_t;

Foo_t foo;

void set_foo(Foo_t arg) {
    foo = arg;
}

void setup() {
    set_foo( quux );
}

void loop() {
}

int main () {
    setup();
    
    while ( 1 ) {
        loop();
    }
}
The Arduino IDE chokes on the same code (minus the main()) though.

But..

If you move the typedef to a header:

Code: Select all

 //  FILENAME: sketch.h

typedef enum { 
    bar, baz, quux 
} Foo_t;
and leave everything else in the main code file:

Code: Select all

//  FILENAME: sketch.c

#include "sketch.h"

Foo_t foo;

void set_foo(Foo_t arg) {
    foo = arg;
}

void setup() {
    set_foo( quux );
}

void loop() {
}
it compiles happily.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”