如何在 C 中定义枚举类型(enum)? [英] How to define an enumerated type (enum) in C?

查看:33
本文介绍了如何在 C 中定义枚举类型(enum)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定使用 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 中定义枚举类型(enum)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆