switch case中的定义
来源:互联网 发布:centos smb unrec 编辑:程序博客网 时间:2024/05/25 21:35
原文:http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement
C语言 switch 中的 case 不能声明变量:
switch (val) { case VAL: // This won't work int newVal = 42; break;case ANOTHER_VAL: ... break;
编译会出现类似 “a label can only be part of a statement and a declaration is not a statement” 的错误。
C语言 switch 中的case是标号,它的执行就像 jump 一样,直接跳到可执行的代码处而忽略初始化,或者跳到另一个以“{}”包围的 scope 中。
Case statements are only 'labels'. This means the compiler will interpret this as a jump directly to the label.The problem here is one of scope. Your curly brackets define the scope as everything inside the 'switch' statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization. The correct way to handle this is to define a scope specific to that case statement and define your variable within it.
switch (val){ case VAL: { // This will work int newVal = 42; break;}case ANOTHER_VAL: ...break;}
- switch case中的定义
- switch case的定义
- switch-case 中的分支中变量定义 编译不通过问题
- switch case 中的break
- switch case中变量定义
- switch case中的局部变量
- Java中的switch-case语句
- Java中的switch-case语句
- Java中的switch-case语句
- Java中的switch-case语句
- Java中的switch-case语句
- java中的switch case语句
- switch case关于定义变量的规定
- 易错点:C++ switch case中定义变量
- switch case 语句内部变量定义
- C++中switch case 中定义变量
- C++语法switch-case中的变量定义(很久在新浪博客的整理)
- C/C++/C# 中的switch case 比较
- Selenium用户指南 - 第三章 Selenium IDE[4]
- android采用IBM-MQTT协议消息推送。
- GDBserver远程调试(汇总)
- sicily--1144 陶陶摘苹果
- 北京迈瑞Mindray笔试
- switch case中的定义
- Selenium用户指南 - 第三章 Selenium IDE[5]
- Android开发中实现多点触摸的方法
- C++设计模式之五:SINGLETON(单件模式)
- 显示内容太多用...显示的SQL语句
- UIImage和IplImage之间的相互转换
- linux中pipe_rw.c的详解
- UIPanGestureRecognizer手势影响UISlider拖动的问题及解决办法
- SSDT HOOK的框架