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 循环在它自己的花括号内
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01