如何在C中定义枚举类型(枚举)? [英] How to define an enumerated type (enum) in C?
本文介绍了如何在C中定义枚举类型(枚举)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道什么是用C枚举正确的语法。我有以下的code:
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
我在做什么错了?
What am I doing wrong?
推荐答案
声明枚举变量是这样做的:
Declaring an enum variable is done like this:
enum {RANDOM, IMMEDIATE, SEARCH} strategy;
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屋!
查看全文