是否允许重叠的 C for 循环变量定义?

发布于 2025-01-12 06:48:26 字数 687 浏览 2 评论 0原文

最近,我不小心写了如下的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 语言定义!

灵感来源:C 版本允许哪些版本你要在 for 循环中声明变量吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲念泪 2025-01-19 06:48:27

这是允许的,通常称为遮蔽,其中最内层作用域的变量遮蔽外部作用域中具有相同名称的任何变量。

正如 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:

... If an identifier designates two different entities in the same
name space, the scopes might overlap. If so, the scope of one entity
(the inner scope) will end strictly before the scope of the other
entity (the outer scope). Within the inner scope, the identifier
designates the entity declared in the inner scope; the entity declared
in the outer scope is hidden (and not visible) within the inner scope.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文