为什么使用不在 UB 范围内的标识符而不是错误

Why is using an identifier not in scope UB and not an error

我在所有未定义行为的列表中引用 ANSI_ISO+9899-1990 -

  • An identifier is used that is not visible in the current scope

为什么使用未定义的变量 UB 而不是错误?我想知道这背后的原因?将 "correct" 之外的所有内容都设为 UB 是否有效?

我知道大多数编译器都将其视为错误。但是为什么标准会这样说呢?

或者标准中没有"error"的概念? c的文法是.* 但部分有UB?

不,标准中有很多错误的概念,只是不是所有的事情都算错误。我先说两件事,这可能对你有帮助:

  1. C89/90 是编纂 现有的 实践, 而不是 创造一种新语言。这意味着有时有必要在事情上妥协,即使它们没有意义。

  2. C99+ 没有 有这个限制,所以某些东西可以被清理。事实上,由于您引用的那段文字似乎在 C99 中消失了,这很可能是清理的内容之一。

回到推理,ANSI C89 基本原理文档是这样说的:

One source of dispute was whether identifiers with external linkage should have file scope even when introduced within a block. The Base Document is vague on this point, and has been interpreted differently by different implementations. For example, the following fragment would be valid in the file scope scheme, while invalid in the block scope scheme:

typedef struct data d_struct ;
first(){
    extern d_struct func();
    /* ...  */
}
second(){
    d_struct n = func();
}

While it was generally agreed that it is poor practice to take advantage of an external declaration once it had gone out of scope, some argued that a translator had to remember the declaration for checking anyway, so why not acknowledge this? The compromise adopted was to decree essentially that block scope rules apply, but that a conforming implementation need not diagnose a failure to redeclare an external identifier that had gone out of scope (undefined behavior).

几乎可以肯定是短语 "has been interpreted differently by different implementations" 导致他们将其标记为 UB 而不是错误。请注意,这里讨论的不是 scope,而是实现是否需要报告您正在尝试使用它的事实。