问题描述
以下文字摘录自 ,由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):
我有些疑问:
- 在C语言中什么情况下编译器不检查
枚举
? -
枚举
常量由于某种原因未进行检查。为什么不?是什么原因 - 由于编译器未检查
enum
,正在使用enum
错误-容易?请解释。
- For what cases in the C language doesn't the compiler check the value of an
enum
? enum
constants are not checked for some reason. Why not? What are the reasons?- Since
enum
is not checked by the compiler, is usingenum
error-prone? Please explain.
推荐答案
-
枚举就像花哨的整数,它比将常量或预处理器宏的整个负载定义为要存储的常量值的名称要好,因为编译器(或编辑器)可以检查您使用的是正确的名称和值以使用正确的类型。另一方面,作为一个int,没有什么可以阻止您输入没有为之命名的值,这有时会有用。
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编译器不检查枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!