For 循环在它自己的花括号内

2022-01-04 00:00:00 for-loop scope c++

我遇到过这种 for 循环布局:

I have come across this for-loop layout:

#include <iostream>
int main()
{
    {
        for (int i = 0; i != 10; ++i)
        {
            std::cout << "delete i->second;" << std::endl;
        }
    }

    {
        for (size_t i = 0; i < 20; ++i)
        {
            std::cout << "delete m_indices[i];" << std::endl;
        }
    }
    return 0;
}

我想知道这层额外的牙套是做什么用的?这在我们的代码库中出现了几次.

I was wondering what this extra layer of braces is for? This appears a few times in our code base.

推荐答案

很久很久以前,VS6 存在并且很流行.然而,它不符合许多 C++ 标准;这在当时是合理的,因为它是在标准正式发布之前(同年)发布的;然而,据我所知,它确实遵守了标准草案.

Once upon a time, many moons ago, VS6 existed and was popular. It failed however to conform to a number of C++ standards; which was reasonable at the time as it was released just before (on the same year) the standard was officially released; it did however adhere to the draft of the standard as far as I'm aware.

草案和官方标准之间变化的一个标准是第一部分中创建的 for 循环变量的生命周期;导致以下代码无法编译

One of the standards that changed between the draft and the official standard, was the lifetime of for loop variables created in the first section; leading to the following code failing to compile

{
    for (int i=0; i<1; ++i){}
    for (int i=0; i<2; ++i){}
}

因为 i 被第二个 for 循环重新定义.

because i was redefined by the second for loop.

虽然其他编译器也有这个bug;我强调 VS6 版本,因为它在标准发布后的几年内仍然是 Visual Studio 的唯一版本,但从未针对此特定问题发布更新;这意味着它产生了更显着的影响.

While other compilers also suffered this bug; I highlight the VS6 one because it remained the only version of visual studio for a number of years after the release of the standard, but never released an update for this particular issue; meaning that it had a more significant impact.

对此的解决方案是强制整个 for 循环进入其自己的范围,如您所示.

A solution to this is to force the whole for loop into its own scope as you have shown.

相关文章