gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:05:46 25 4
gpt4 key购买 nike

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

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

为什么使用 undefined variable UB 而不是错误?我想知道这背后的原因?将所有不“正确”的内容都作为 UB 有效吗?

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

或者标准中没有“错误”的概念?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).

几乎可以肯定的是,“已被不同的实现以不同方式解释”这句话导致他们将其标记为 UB 而不是错误。请注意,这里讨论的不是范围,而是实现是否需要报告您正在尝试使用它的事实。

关于c - 为什么使用不在 UB 范围内的标识符而不是错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42546831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com