Debug日志:C++中的一个switch-case陷阱

来源:互联网 发布:飞鱼网络电视电脑版 编辑:程序博客网 时间:2024/05/19 18:12

先看这段代码:

#include <iostream>using namespace std;int main(){for(int i = 0; i < 10; i++){switch(i){case 0 :int* ptr = new int;cout << "case 0 :" << endl;cout <<"赋值前 ptr = " << ptr << endl;*ptr = 9;cout << "赋值后 ptr = " << ptr << endl;cout << "sizeof(ptr) = " << sizeof(ptr) << endl << endl;delete ptr;break;case 1 :int* array = new int[10];cout << "case 1 :" << endl;cout << "赋值前 ";for(int j = 0; j < 10; j++)cout << "array[" << j << "] = " << array[j] << '\t';cout << endl;for(int j = 0; j < 10; j++)array[j] = j + 10;cout << "赋值后 ";for(int j = 0; j < 10; j++)cout << "array[" << j << "] = " << array[j] << '\t';cout << endl;cout << "sizeof(array[0]) = " << sizeof(array[0]) << endl;cout << "sizeof(array) = " << sizeof(array) << endl;delete[] array;break;default : break;}}return 0;}
编译器会报错:

但是在case后的语句块前后加上花括号{}就编译通过了:

#include <iostream>using namespace std;int main(){for(int i = 0; i < 10; i++){switch(i){case 0 :{int* ptr = new int;cout << "case 0 :" << endl;cout <<"赋值前 ptr = " << ptr << endl;*ptr = 9;cout << "赋值后 ptr = " << ptr << endl;cout << "sizeof(ptr) = " << sizeof(ptr) << endl << endl;delete ptr;break;}case 1 :{int* array = new int[10];cout << "case 1 :" << endl;cout << "赋值前 ";for(int j = 0; j < 10; j++)cout << "array[" << j << "] = " << array[j] << '\t';cout << endl;for(int j = 0; j < 10; j++)array[j] = j + 10;cout << "赋值后 ";for(int j = 0; j < 10; j++)cout << "array[" << j << "] = " << array[j] << '\t';cout << endl;cout << "sizeof(array[0]) = " << sizeof(array[0]) << endl;cout << "sizeof(array) = " << sizeof(array) << endl;delete[] array;break;}default : break;}}return 0;}

这种情况的具体原因可能是因为申请动态内存时,动态变量的作用域问题。参见博客园的一篇文章:http://www.cnblogs.com/dolphin0520/p/3729579.html  《浅析C/C++中的switch/case陷阱》。

原创粉丝点击