gpt4 book ai didi

c++ - 我可以依靠我的编译器来诊断 TU 中的类型不匹配吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:19:51 26 4
gpt4 key购买 nike

通过规范搜索,似乎我的编译器不需要诊断这样的错误

extern int a;
extern float a;

我以前认为我的编译器需要对此进行诊断,但规范说(强调由我添加)

After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.

事实上,我发现了编译器不关心的情况。例如,GCC 和 clang 接受以下内容

void g() { int f(); } 
void h() { float f(); }

由于违反不需要诊断的规则意味着整个程序不再需要诊断,这意味着以下格式错误的程序也不需要诊断(参见 1.4p2)。幸运的是,GCC 和 Clang 都可以诊断它们。

int f();
float f();

这段代码在翻译时的行为实际上是未定义的。这是什么原因?为什么规范不能要求拒绝此类案例并要求对这些案例进行诊断?

最佳答案

我认为您引用的规则是针对整个程序的。如果一个 TU 具有 extern int a; 而另一个 TU 具有 extern float a; 则不需要诊断,因为单独的翻译使其不可能 - 问题只能在链接处检测到最好的时间。

但如果两个声明都出现在一个 TU 中,我确定需要进行诊断。也许是 3.3/4?这(大致)要求一个范围内的所有名称声明都引用同一实体。

关于c++ - 我可以依靠我的编译器来诊断 TU 中的类型不匹配吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6011517/

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