我不确定使用C枚举的正确语法是什么。我有以下代码:

enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;

但这不会编译,错误如下:
error: conflicting types for ‘strategy’
error: previous declaration of ‘strategy’ was here

我做错什么了?

最佳答案

声明枚举变量的过程如下:

enum strategy {RANDOM, IMMEDIATE, SEARCH};
enum strategy my_strategy = IMMEDIATE;

但是,您可以使用typedef来缩短变量声明,如下所示:
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy my_strategy = IMMEDIATE;

使用命名约定来区分类型和变量是一个好主意:
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy_type;
strategy_type my_strategy = IMMEDIATE;

关于c - 如何在C中定义枚举类型(枚举)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31769553/

10-11 15:12