[英]Use switch cases in an if statement
我們可以使用條件在 switch 語句中包含 case 嗎?
我的代碼:
switch(menu_option)
{
if (g_logged_in)
{
case 'L':
cout << "Login Menu\n";
break;
case 'S':
cout << "Signup Menu\n";
break;
}
case 'A':
foo();
break;
case 'B':
bar();
break;
default:
cout << "Invalid Option!\n";
}
當我編譯文件時,我收到一個錯誤
[pewpew@Sierra cpp-something]$ c++ src/main.cc -o main.out
src/main.cc: In function 'int main()':
src/main.cc:53:13: warning: statement will never be executed [-Wswitch-unreachable]
53 | if (g_logged_in)
| ^~
完全不可能嗎?
目前,程序控制永遠不會到達if (g_logged_in)
,所以它永遠不會被評估。 您有用的編譯器發出警告。
實際上,雖然switch
塊只不過是一組受控的goto
語句。 你可以強迫它
switch(menu_option){
foo:
if (g_logged_in){
帶有goto foo;
程序控制到達的地方,盡管由於可讀性和可維護性,這種想法是不明智的。 以下代碼片段是“Hello World!”的重新表述。 程序:
#include <iostream>
int main(){
switch (1){
foo:
if (true){
case 0:
std::cout << " World!\n";
break;
case 1:
std::cout << "Hello";
goto foo;
}
}
}
有關switch
塊內交錯控制循環的實際用例,請參閱 Duff 的設備: https : //en.wikipedia.org/wiki/Duff%27s_device
您的代碼上方沒有“案例”。 你不能這樣做。 這種情況很可能被編譯成一條 CPU 指令,該指令僅適用於整數。 您必須使用 case 並對兩種情況執行 if() 兩次。
您不能有條件地指定case
語句。 你將不得不做更多這樣的事情:
switch (menu_option)
{
case 'L':
// in C++17 and later, you can uncomment the following
// attribute to avoid a compiler warning...
//
// [[fallthrough]];
case 'S':
if (g_logged_in)
{
if (menu_option == 'L')
cout << "Login Menu\n";
else
cout << "Signup Menu\n";
}
else
cout << "Invalid Option!\n";
break;
case 'A':
foo();
break;
case 'B':
bar();
break;
default:
cout << "Invalid Option!\n";
break;
}
或這個:
switch (menu_option)
{
case 'A':
foo();
break;
case 'B':
bar();
break;
default:
if (g_logged_in)
{
if (menu_option == 'L')
{
cout << "Login Menu\n";
break;
}
if (menu_option == 'S')
{
cout << "Signup Menu\n";
break;
}
}
cout << "Invalid Option!\n";
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.