您能够访问变量的区域称为其作用域。对于局部非静态变量,此范围的边界用大括号 ( {
... }
) 定义,因此:
{
...
int a = 0;
switch (option)
{
case 1:
{
int b;
a = 2;
} // <-- the scope of b ends here
...
}
} // <-- the scope of a ends here
请注意,randomVariable
必须在其中声明,case 1:
因为这是创建数组的选项
由于您使用 C++ 编程,而不是 C 样式的数组 use std::vector
,它是在连续内存块中保存元素的容器,就像数组一样,但它的大小可以改变:
#include <vector>
...
{
std::vector<int> myVector;
switch (option)
{
case 1:
{
int size;
// value retrieved in run-time is assigned into size here
myVector.resize(size, 0);
}
case 2:
{
// you can use your vector here:
if (myVector.size() > 3)
myVector[2] = 7;
}
...
}
} // <-- end of myVector's scope
在此示例中,myVector.resize(size, 0);
调整 vector 内部使用的内存大小,使其足以容纳size
元素,如果其大小已增加,它还会将新元素插入此内存并将它们初始化为0
. 这里重要的是,这myVector
是一个具有自动存储持续时间的对象,这意味着当执行超出其定义的范围时,内存会被自动清理。这使您免于在使用动态分配的 C 样式数组的情况下必须处理的丑陋的内存管理。