エラー:ケースラベルにジャンプ


229

私はswitchステートメントの使用を含むプログラムを書きました...しかし、コンパイル時にそれは示しています:

エラー:ケースのラベルに移動します。

なぜそれを行うのですか?

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

using namespace std;

class contact
{
public:
    string name;
    int phonenumber;
    string address;
    contact() {
        name= "Noname";
        phonenumber= 0;
        address= "Noaddress";
    }
};

int main() {
    contact *d;
    d = new contact[200];
    string name,add;
    int choice,modchoice,t;//Variable for switch statement
    int phno,phno1;
    int i=0;
    int initsize=0, i1=0;//i is declared as a static int variable
    bool flag=false,flag_no_blank=false;

    //TAKE DATA FROM FILES.....
    //We create 3 files names, phone numbers, Address and then abstract the data from these files first!
    fstream f1;
    fstream f2;
    fstream f3;
    string file_input_name;
    string file_input_address;
    int file_input_number;

    f1.open("./names");
    while(f1>>file_input_name){
        d[i].name=file_input_name;
        i++;
    }
    initsize=i;

    f2.open("./numbers");
    while(f2>>file_input_number){
        d[i1].phonenumber=file_input_number;
        i1++;
    }
    i1=0;

    f3.open("./address");
    while(f3>>file_input_address){
        d[i1].address=file_input_address;
        i1++;
    }

    cout<<"\tWelcome to the phone Directory\n";//Welcome Message
    do{
        //do-While Loop Starts
        cout<<"Select :\n1.Add New Contact\n2.Update Existing Contact\n3.Display All Contacts\n4.Search for a Contact\n5.Delete a  Contact\n6.Exit PhoneBook\n\n\n";//Display all options
        cin>>choice;//Input Choice from user

        switch(choice){//Switch Loop Starts
        case 1:
            i++;//increment i so that values are now taken from the program and stored as different variables
            i1++;
            do{
                cout<<"\nEnter The Name\n";
                cin>>name;
                if(name==" "){cout<<"Blank Entries are not allowed";
                flag_no_blank=true;
                }
            }while(flag_no_blank==true);
            flag_no_blank=false;
            d[i].name=name;
            cout<<"\nEnter the Phone Number\n";
            cin>>phno;
            d[i1].phonenumber=phno;
            cout<<"\nEnter the address\n";
            cin>>add;
            d[i1].address=add;
            i1++;
            i++;
            break;//Exit Case 1 to the main menu
        case 2:
            cout<<"\nEnter the name\n";//Here it is assumed that no two contacts can have same contact number or address but may have the same name.
            cin>>name;
            int k=0,val;
            cout<<"\n\nSearching.........\n\n";
            for(int j=0;j<=i;j++){
                if(d[j].name==name){
                    k++;
                    cout<<k<<".\t"<<d[j].name<<"\t"<<d[j].phonenumber<<"\t"<<d[j].address<<"\n\n";
                    val=j;
                }
            }
            char ch;
            cout<<"\nTotal of "<<k<<" Entries were found....Do you wish to edit?\n";
            string staticname;
            staticname=d[val].name;
            cin>>ch;
            if(ch=='y'|| ch=='Y'){
                cout<<"Which entry do you wish to modify ?(enter the old telephone number)\n";
                cin>>phno;
                for(int j=0;j<=i;j++){
                    if(d[j].phonenumber==phno && staticname==d[j].name){
                        cout<<"Do you wish to change the name?\n";
                        cin>>ch;
                        if(ch=='y'||ch=='Y'){
                            cout<<"Enter new name\n";
                            cin>>name;
                            d[j].name=name;
                        }
                        cout<<"Do you wish to change the number?\n";
                        cin>>ch;
                        if(ch=='y'||ch=='Y'){
                            cout<<"Enter the new number\n";
                            cin>>phno1;
                            d[j].phonenumber=phno1;
                        }
                        cout<<"Do you wish to change the address?\n";
                        cin>>ch;
                        if(ch=='y'||ch=='Y'){
                            cout<<"Enter the new address\n";
                            cin>>add;
                            d[j].address=add;
                        }
                    }
                }
            }
            break;
        case 3 : {
            cout<<"\n\tContents of PhoneBook:\n\n\tNames\tPhone-Numbers\tAddresses";
            for(int t=0;t<=i;t++){
                cout<<t+1<<".\t"<<d[t].name<<"\t"<<d[t].phonenumber<<"\t"<<d[t].address;
            }
            break;
                 }
        }
    }
    while(flag==false);
    return 0;
}

1
コンパイルしようとしているコードは何ですか?どのコンパイラを使用していますか?各caseブロックを中括弧で囲みましたか?
Cody Grey

2
これは、印象的なラウンドアバウト交差点のエラーメッセージです
jozxyqk

回答:


437

問題は、1つで宣言された変数は、明示的なブロックが使用されない限りcase、後続ので引き続き表示されますが、初期化コードが別のに属しているため初期化されませんcase{ }case

次のコードでfooは、1に等しい場合はすべて問題iありませんが、2に等しい場合は、存在するがおそらくガベージが含まれている変数を誤って使用します。

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;
}

1
その他の説明については、この修正されたLLVMバグレポートを参照してください:llvm.org/bugs/show_bug.cgi?id
Francesco

70

caseステートメントでの新しい変数の宣言が問題の原因です。すべてのcaseステートメントを{}と、新しく宣言された変数のスコープが、問題を解決する現在実行中のケースに制限されます。

switch(choice)
{
    case 1: {
       // .......
    }break;
    case 2: {
       // .......
    }break;
    case 3: {
       // .......
    }break;
}    

クリーナーの修正手順
yc_yuy 2014年

中かっこ内にbreakステートメントを置いても問題はありませんか?
Vishal Sharma

10

一部の初期化を飛び越えるためのC ++ 11標準

ヨハネスDが説明しました。

C ++ 11 N3337標準のドラフト 6.7「宣言文は、」言います:

3ブロックに転送することは可能ですが、初期化で宣言をバイパスする方法ではできません。自動ストレージ期間の変数がスコープ内にないポイントからスコープ内のポイントにジャンプするプログラム(87)は、変数がスカラー型、自明なデフォルトコンストラクターと自明なクラス型を持たない限り、形式が正しくありません。デストラクタ、これらのタイプのいずれかのcv修飾バージョン、または前述のタイプのいずれかの配列であり、初期化子なしで宣言されています(8.5)。

87)switchステートメントの条件からcaseラベルへの転送は、この点でジャンプと見なされます。

[例:

void f() {
   // ...
  goto lx;    // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;    // OK, jump implies destructor
              // call for a followed by construction
              // again immediately following label ly
}

—最後の例]

GCC 5.2以降、エラーメッセージは次のようになります。

の初期化を横切る

C

Cが許可:c99 goto過去の初期化

C99 N1256標準草案の附属書I「共通の警告が」言います:

2自動ストレージ期間を持つオブジェクトの初期化を持つブロックがジャンプインされます


6

JohannesDの答えは正しいですが、問題のある側面については完全に明確ではないと思います。

彼が与える例はi、ケース1で変数を宣言して初期化し、次にケース2でそれを使用しようとします。彼の引数は、スイッチがケース2に直接進んだ場合、i初期化されずに使用されることであり、これがコンパイルの理由です。エラー。この時点で、あるケースで宣言された変数が他のケースで使用されない場合は問題ないと考えることができます。例えば:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

両方ijは、それらを宣言するケース内でのみ使用されるため、このプログラムのコンパイルを期待できます。残念ながら、C ++ではコンパイルできません。CiroSantilli包子露宪六四事件法轮機能で説明されているように、にジャンプすることはできません。case 2:これによりi、の初期化で宣言がスキップされ、case 2使用されていませんiれ、これはまだC ++では禁止されています。

興味深いことに、(いくつかの調整を#ifdefする#includeための適切なヘッダ、およびラベル後セミコロン、ラベルのみ文を続けることができ、および宣言はC内のステートメントとしてカウントされない)、このプログラムはない Cとしてコンパイル。

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

http://rextester.comのようなオンラインコンパイラのおかげで、MSVC、GCC、またはClangを使用して、CまたはC ++としてコンパイルすることができます。Cは常に機能します(STDINを設定することを忘れないでください)。C++はそれを受け入れないためです。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.