Returning an enum from a function in C?

后端 未结 4 1686
醉酒成梦
醉酒成梦 2020-12-14 00:51

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
};


        
相关标签:
4条回答
  • 2020-12-14 01:35
    enum Foo
    {
       BAR,
       BAZ
    };
    

    In C, the return type should have enum before it. And when you use the individual enum values, you don't qualify them in any way.

    enum Foo testFunc()
    {
        enum Foo temp = BAR;
        temp = BAZ;
        return temp;
    }
    
    0 讨论(0)
  • 2020-12-14 01:36

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

    enum Foo testFunc(){
      return BAR;
    }
    
    0 讨论(0)
  • 2020-12-14 01:39

    I think some compilers may require

    typedef enum tagFoo
    {
      BAR,
      BAZ,
    } Foo;
    
    0 讨论(0)
  • 2020-12-14 01:42

    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;
    }
    
    0 讨论(0)
提交回复
热议问题