為什麼 C/C++ 中的 switch 語句無法宣告變數?
變數可以在 switch 語句中宣告。只需在 switch 語句中宣告它們,並在新範圍內使用它們即可。例如,
示例
#include<iostream>
using namespace std;
int main() {
int i = 10;
switch(i) {
case 2:
//some code
break;
case 10:{
int x = 13;
cout << x;
}
}
return 0;
}輸出
這將生成以下輸出
13
如果你嘗試在開放環境中宣告變數,可能會遇到錯誤,因為跳轉到 case 標籤與使用 goto 相同,因此不允許在與區域性變數宣告處於相同範圍且可能在該範圍內其他地方使用該變數時跳過該宣告。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP