如果在函数中声明了枚举,那么范围是什么?

时间:2016-07-21 18:22:41

标签: c

枚举是私有的吗?

void doSomething()
{
   enum cmds {
      A, B, C
   }
}

4 个答案:

答案 0 :(得分:4)

enum cmds类型和枚举成员ABC是函数范围的本地。

请注意,虽然枚举不会为其成员常量引入新的作用域,但它们确实在包含作用域内,在本例中为函数体。

int doSomething(void)
{
    enum cmds {
        A, B, C  // 0, 1, 2
    };

    return C;  // returns 2
}

int anotherThing(void)
{
    enum cmds {
        C, D, E  // 0, 1, 2
    };
    return C;  // returns 0
}

Run the example code here on Coliru

答案 1 :(得分:2)

与几乎任何其他声明一样,块内定义的enum类型是该块的本地类型。

在你的情况下:

void doSomething()
{
   enum cmds {
      A, B, C
   }
}

该块恰好是函数的最外层块,但不一定是:

void doSomething(void) {
    if (condition) {
        enum cmds {A, B, C};
        // The type and constants are visible here ...
    }
    // ... but not here.
}

(转到标签是C中唯一实际具有功能范围的实体。)

答案 2 :(得分:1)

  

枚举不会引入新范围。

参考this

答案 3 :(得分:0)

正如您所提到的那样,您定义的enum cmd只能才能在此功能中使用。但是如果在头文件中定义枚举,则可以在任何包含此标头的c文件中使用枚举的所有项目。

它与普通变量相同,但有时,该项可以用作marco(实际上它只是一个整数)。在某些情况下这非常方便。