For loop inside its own curly braces(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){}
}
因为 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.
这篇关于For 循环在它自己的花括号内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:For 循环在它自己的花括号内
				
        
 
            
        基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				