简体   繁体   English

我们可以在C中使用带有不同枚举标签的多个常量吗

[英]Can we use multiple constants with different enums tags in C

I have following code: 我有以下代码:

enum tag1 {
 n1, n2, n3
};

enum tag2 {
 n4, n5, n1
};

Now, I got an error, n1 are used two times 现在,我得到一个错误, n1被使用了两次

So my question is what is the use of enum tags when enum constants doesn't have a scope. 所以我的问题是,当枚举常量没有作用域时, enum tags的用途是什么。

No, you cannot use it like this. 不,您不能像这样使用它。 Enums in "C" are not strongly typed. “ C”中的枚举不是强类型的。

Using enums increase the level of abstraction and lets the programmer think about what the values mean rather than worry about how they are stored and accessed. 使用枚举可提高抽象水平,并使程序员可以思考值的含义,而不必担心如何存储和访问它们。 This reduces the occurrence of bugs. 这减少了错误的发生。

Enums have these benefits: 枚举具有以下优点:

  • They restrict the values that the enum variable can take 它们限制了enum变量可以采用的值
  • They force you to think about all the possible values that the enum can take. 它们迫使您考虑枚举可以采用的所有可能的值。
  • They are a constant rather than a number, increasing readability of the source code 它们是常量而不是数字,从而提高了源代码的可读性

You can use enum tags to declare variables of type of the corresponding enum without using a typedef : 您可以使用enum标签来声明相应enum类型的变量,而无需使用typedef

enum tag1 varName = n5;

Unfortunately, there is no way to have several enum s sharing a member in the same translation unit. 不幸的是,没有办法让几个enum在同一个翻译单元中共享一个成员。 Obviously, you can define your two enum s in different headers, and make full use of them, as long as the two headers are not included in the same C file. 显然,您可以在不同的标头中定义两个enum ,并充分利用它们,只要两个标头不包含在同一个C文件中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM