我知道可以在switch语句中创建但不能初始化一个变量。但是我想知道在后续执行switch语句期间,是否已将创建的变量保留在内存中?
我假设命名变量CNT的纽利创建每次执行switch语句。因此,在案例标签内的代码分配一个值之前,cnt的值始终是未定义的!
#include <iostream>
using namespace std;
int main() {
int iarr[6] = {0, 1, 1, 1, 0, 1};
for (int i : iarr) {
switch (i) {
int cnt;
case 0:
// it is illegal to initalize value, therefore we assign an
// inital value now
cout << "Just assign 0 to the variable cnt.\n";
cout << (cnt = 0) << "\n";
break;
case 1:
cout << "Increment variable cnt.\n";
cout << ++cnt << "\n";
break;
}
}
return 0;
}
但是至少在我的机器上和测试期间,在switch语句中定义的变量cnt保留了它的值。我认为这是一个误报,并且我的系统是否(运气不好)总是访问相同的内存区域?
输出(GCC 4.9):
$ g++ -o example example.cpp -std=gnu++11 -Wall -Wpedantic -fdiagnostics-color && ./example
Just assign 0 to the variable cnt.
0
Increment variable cnt.
1
Increment variable cnt.
2
Increment variable cnt.
3
Just assign 0 to the variable cnt.
0
Increment variable cnt.
1
谢谢
编译器不会显式初始化变量。因此,它具有一个值,该值存储在为变量分配的内存中。但是根据C ++标准,每次将控件传递到switch语句时都会创建变量。
实际上,没有什么可以阻止编译器在基于范围的复合语句中使用的其他代码块中使用相同的内存。
根据C ++标准
2具有自动存储持续时间(3.7.3)的变量在每次执行它们的声明语句时都会初始化。在该块中声明的具有自动存储持续时间的变量在从该块退出时被销毁(6.6)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句