如何在C中定义枚举类型(枚举)? [英] How to define an enumerated type (enum) in C?
本文介绍了如何在C中定义枚举类型(枚举)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道使用C枚举的正确语法是什么。我有以下代码:
I'm not sure what is the proper syntax for using C enums. I have the following code:
enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy = IMMEDIATE;
但是这不能编译,出现以下错误:
But this does not compile, with the following error:
error: conflicting types for ‘strategy’
error: previous declaration of ‘strategy’ was here
我做错了什么?
推荐答案
声明枚举变量是这样完成的:
Declaring an enum variable is done like this:
enum strategy {RANDOM, IMMEDIATE, SEARCH};
enum strategy my_strategy = IMMEDIATE;
但是,您可以使用 typedef
缩短变量声明,如下所示:
However, you can use a typedef
to shorten the variable declarations, like so:
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy;
strategy my_strategy = IMMEDIATE;
有一个命名约定来区分类型和变量是个好主意:
Having a naming convention to distinguish between types and variables is a good idea:
typedef enum {RANDOM, IMMEDIATE, SEARCH} strategy_type;
strategy_type my_strategy = IMMEDIATE;
这篇关于如何在C中定义枚举类型(枚举)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文