为什么C编译器不检查枚举? [英] Why isn't an enum checked by the C compiler?

查看:217
本文介绍了为什么C编译器不检查枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下文字摘录自 C编程语言,第二版 ,由C语言的创建者编写(因此我认为它是正确的):

The following text is an excerpt from C Programming Language, 2nd Edition, written by the creator of the C language (so I presume it is correct):


尽管可以声明枚举类型的变量,但编译器无需检查您存储在此类变量中的内容是否为枚举的有效值。

Although variables of enum types may be declared, compilers need not check that what you store in such a variable is a valid value for the enumeration.

我有些疑问:


  1. 在C语言中什么情况下编译器不检查枚举

  2. 枚举常量由于某种原因未进行检查。为什么不?是什么原因

  3. 由于编译器未检查 enum ,正在使用 enum 错误-容易?请解释。

  1. For what cases in the C language doesn't the compiler check the value of an enum?
  2. enum constants are not checked for some reason. Why not? What are the reasons?
  3. Since enum is not checked by the compiler, is using enum error-prone? Please explain.


推荐答案


  1. 枚举就像花哨的整数,它比将常量或预处理器宏的整个负载定义为要存储的常量值的名称要好,因为编译器(或编辑器)可以检查您使用的是正确的名称和值以使用正确的类型。另一方面,作为一个int,没有什么可以阻止您输入没有为之命名的值,这有时会有用。

  1. An enumeration is like a fancy integer, and it's better than defining a whole load of constants or preprocessor macros as names for the constant values you want to store, because a compiler (or editor) can check that you're using the right names and values to go with the right type. On the other hand, being just an int, there's nothing stopping you putting in a value you didn't make a name for, which is occasionally useful.

不能在所有情况下都对其进行检查。如果您将两个数字加在一起以得到将要放入枚举类型的变量中的值怎么办?它可以是在运行时生成的任何值,因此无法检查(至少没有很多开销)。

They can't be checked in every case. What if you add two numbers together to get the value that's going to be put in the enum-typed variable? It could be any value, generated at runtime, so it can't be checked (without a lot of overhead, at least).

C中的所有内容都是不安全几乎没有任何功能可以使编译器完全阻止您进行滥用。枚举是安全的,因为它们可以有效地防止程序员出错和混乱,而不是因为它们会阻止您执行愚蠢的操作。

Everything in C is unsafe; there's practically no feature which the compiler can totally prevent you from abusing. enums are safe because they are effective at preventing programmer error and confusion, not because they stop you doing something stupid.

这篇关于为什么C编译器不检查枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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