For循环在其自己的花括号内 [英] For loop inside its own curly braces

查看:161
本文介绍了For循环在其自己的花括号内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过这种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){}
}

因为第二次for循环重新定义了i.

because i was redefined by the second for loop.

其他编译器也遇到了此错误;我重点介绍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.

这篇关于For循环在其自己的花括号内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆