c - K & R C 变量名称

标签 c

我对K&R C中关于变量名的内容有些迷惑,原文如下:

At least the first 31 characters of an internal name are significant. For function names and external variables, the number may be less than 31, because external names may be used by assemblers and loaders over which the language has no control. For external names, the standard guarantees uniqueness only for 6 characters and a single case. Keywords like if, else, int, float, etc., are reserved: you can't use them as variable names. They must be in lower case. It's wise to choose variable names that are related to the purpose of the variable, and that are unlikely to get mixed up typographically. We tend to use short names for local variables, especially loop indices, and longer names for external variables.

让我感到困惑的是外部名称,标准只保证 6 个字符和一个案例的唯一性。这是否意味着对于外部名称,只有 6 个前导字符有效,其余字符都被忽略?比如我们定义了两个外部变量myexvar1和myexvar2,编译器会把这两个变量当成一个吗?如果这是真的,为什么他们建议我们为外部变量使用更长的名称?

最佳答案

Does it means that for external names, only the 6 leading chars are valid and remaining chars are all ignored? For example, we defined two external variable myexvar1 and myexvar2, the compiler will treat these two variables as one?

是的,这在 1990 年是正确的。或者更确切地说,外部标识符的 6 个唯一前导字符是 C90 标准为编译器设置的最小限制。这当然是疯狂的——这就是为什么这个限制在 C99 中增加到 31。

在实践中,大多数 C90 编译器至少有 31 个唯一字符用于内部和外部标识符。


If this is true, why they advise us to use longer names for external variables?

不确定他们是否建议这样做。但是 K&R 中使用的编码风格通常很糟糕,所以绝对不是一本你应该引用编码风格建议的书。


在现代 C 中,要求 (C17 5.2.4.1) 我们有:

63 significant initial characters in an internal identifier or a macro name

31 significant initial characters in an external identifier

所以不用太担心恐龙面临哪些限制,而是遵循现代标准C。

正如在另一个答案中指出的那样,即使外部标识符的 31 个重要初始字符的限制也被列为过时,这意味着在未来的标准中这可能会进一步增加到 255 个。

关于c - K & R C 变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54921374/

相关文章:

c++ - 如何在 C 预处理器中合并符号名称和符号值

c - 给出段错误和 idk 在哪里

将 int 连接到字符串或在 C 中转换

c++ - segmentation 故障的常见原因的明确列表

c - 为什么在c中调用函数时程序会崩溃?

c - 当使用 realloc 并将内存写入新地址时会发生什么?

c - STM8S Cosmic编译器定义

c - 第 15 位数字后小数精度丢失 - PI 错误

c - Bluez D 总线 : Bluetooth speaker Play/Pause/Next/Previous button handling

c - 如何实现不同情况下的切换?