switch ステートメントを使用するプログラムを作成しましたが、コンパイル時に次のように表示されます。
エラー: ケース ラベルにジャンプします。
なぜそうなるのでしょうか?
#include <iostream>
int main()
{
int choice;
std::cin >> choice;
switch(choice)
{
case 1:
int i=0;
break;
case 2: // error here
}
}
ベストアンサー1
問題は、明示的なブロックが使用されない限り、1 つの で宣言された変数case
は後続の で引き続き表示されますが、初期化コードが別の に属しているため、それらの変数は初期化されないことです。case
{ }
case
次のコードでは、 がfoo
1 の場合はすべて正常ですが、 が 2 の場合、i
存在するもののおそらくゴミを含む変数を誤って使用してしまいます。
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
明示的なブロックでケースをラップすると、問題は解決します。
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
編集
さらに詳しく説明すると、switch
ステートメントは の特別な種類のものにすぎません。の代わりにgoto
を使用した、同じ問題を示す類似のコードを次に示します。goto
switch
int main() {
if(rand() % 2) // Toss a coin
goto end;
int i = 42;
end:
// We either skipped the declaration of i or not,
// but either way the variable i exists here, because
// variable scopes are resolved at compile time.
// Whether the *initialization* code was run, though,
// depends on whether rand returned 0 or 1.
std::cout << i;
}