Syntax for a function returning an enumerated type

The Arduino compiler will let me define an enumerated type, but not a function returning that type. Everything works fine for a function returning an int that I then cast to the enum, but this is ugly. Here is the simplest example:

enum    MyType    {  Zero, One, Two  };  // OK
int     UrFunc    {  return (Zero);  }   // Also OK
MyType  MyFunc()  {  return (Zero);  }   // Error: 'MyType' does not name a type

Alternate form using typedef, same results:

typedef  enum MyType    { Zero, One, Two } MyType_t;  // OK
MyType_t      MyFunc()  { return (Zero); }            // same error

Any ideas?

Move the enum definition to a header file (to another "tab").

Hi,

The problem here is that the enumerated type doesn't exist for the function prototypes that the Arduino automatically generates for you.

The complier must know what a function looks like before you can use it in your C++ program. You tell the complier what the function looks like using a prototype: essentially the function definition without its body. In your case that would be:

MyType_t MyFunc();

The prototype is declared at the top of the file, or (more usually) in a separate header file.

In the Arduino IDE, prototypes are created for you automatically, and placed at the start of the file. Unfortunately because the typdef doesn't get moved to the start of the file, the enumerated type doesn't exist when the complier encounters the prototype. Hence the error.

Your best solution is to put the type definition in a separate header file (ie separate tab). Perhaps call it "Types.h" Then in your main file, #include "Types.h".

HTH
paul

To clarify a bit on Paul's excellent answer: if you don't want to create a separate header file, you can simply add the prototype to the main .ino file (after the enum or struct typedef) and the IDE won't auto-generate another "hidden" one at the start of the file when you build.