是否允许重叠的 C for 循环变量定义?
最近,我不小心写了如下的C代码:
for (size_t i = 0; i < SOME_VALUE; ++i)
{
for (size_t i = 0; i < ANOTHER_VALUE; ++i)
{
// do work with 'i' from inner loop *WITHOUT* any disruption to 'i' from outer loop
}
}
仔细阅读代码,我发现了这个“bug”。然而,在运行时,它并没有引起任何问题。需要明确的是,我的代码是使用相对较新版本的 MinGW-w64 编译的,以创建本机 Win32 二进制文件。
当然,代码可以工作,但我很惊讶这是允许的,更惊讶的是我的 GCC-ish 编译器没有抱怨它! (这个错误有 GCC 警告选项吗?)
有人可以解释为什么这是允许的,以及为什么内部和外部 i
变量不会冲突/破坏?理想情况下,有人可以向我指出允许(并支持)这种行为的官方 ISO-ish C 语言定义!
Recently, I accidentally wrote C code that looks like this:
for (size_t i = 0; i < SOME_VALUE; ++i)
{
for (size_t i = 0; i < ANOTHER_VALUE; ++i)
{
// do work with 'i' from inner loop *WITHOUT* any disruption to 'i' from outer loop
}
}
Reading the code closely, I discovered this "bug". However, at runtime, it did not cause any issues. To be clear, my code was compiled with a relatively recent version of MinGW-w64 to create a native Win32 binary.
Sure, the code works, but I am surprised this is allowed, and even more surprised that my GCC-ish compiler did not complain about it! (Is there a GCC warning option for this mistake?)
Can someone explain why this is allowed, and why the inner and outer i
variables do not conflict / disrupt? Ideally, someone can point me to official ISO-ish C language definition that allows (and supports) this behaviour!
Inspired by: What versions of C allow you to declare variables in for loops?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是允许的,通常称为遮蔽,其中最内层作用域的变量遮蔽外部作用域中具有相同名称的任何变量。
正如 C 标准:
This is allowed, and is commonly referred to as shadowing, where the variable at the innermost scope shadows any variable with the same name at an outer scope.
This is explicitly allowed as specified in section 6.2.1p4 of the C standard regarding Scope of Identifiers: