错误:跳转到案例标签


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块都用大括号括起来了?
科迪·格雷

2
那是一条令人印象深刻的回旋错误消息
jozxyqk

Answers:


437

问题在于,除非使用显式块,否则在一个变量中声明的变量在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。这是一段显示相同问题的相似代码,但是使用了a goto而不是a 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
有关其他说明,请参见此
Francesco

70

引起问题的原因是在case语句中声明新变量。将所有case语句括起来{}会将新声明的变量的范围限制为当前正在执行的情况,从而解决了该问题。

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

清洁工修复说明
yc_yuy 2014年

如果将break语句放在花括号内,会不会有任何问题?
维沙尔·沙尔玛

10

跳过一些初始化的C ++ 11标准

JohannesD现在对标准进行了解释。

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转到初始化之后

C99 N1256标准草案附件一“共同警告”说:

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 ++中它无法编译:正如Ciro Santilli包子露宪六四事件法轮功所述,我们根本无法跳转到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 ++没有编译器接受它。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.