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陷阱》。
阅读全文
0 0
- Debug日志:C++中的一个switch-case陷阱
- 浅析C/C++中的switch/case陷阱
- 浅析C/C++中的switch/case陷阱
- 浅析C/C++中的switch/case陷阱
- 浅析C/C++中的switch/case陷阱
- C/C++中的switch/case陷阱
- switch-case陷阱
- C/C++/C# 中的switch case 比较
- c语言中的switch case语句
- C语言中的switch case比较
- switch case中的定义
- switch case 中的break
- c#switch-case
- 【JavaSE】关于switch case的陷阱
- 浅析内存陷阱以switch-case举例
- switch case 在C中的编译链接规则
- C语言中break在switch-case中的作用
- switch case中的局部变量
- 使用jquery提供的抛物插件,实现添加商品出现抛物线动画
- 第七天:对比度亮度调整与通道分离
- spark 启动sql Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
- HDOJ1574 RP问题 动态规划 简单DP
- Error: could not open `C:\Java\jre7\lib\amd64\jvm.cfg';JAVA_HOME环境变量失效的解决办法
- Debug日志:C++中的一个switch-case陷阱
- 【已解决】Ubuntu / Linux 安装USB无线网卡( tp-link TL-WN725N rtl8188eu )
- Spark SQL笔记——技术点汇总
- 在windows下安装lupa库
- Apriori算法进行关联分析
- Unity Attribute的使用总结
- 指针数组和数组指针
- stm32 rtc 实时时钟
- 软件测试面试题个人归纳总结