错误:跳转到案例标签

时间:2011-04-16 09:05:22

标签: c++

我编写了一个涉及使用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;
}

4 个答案:

答案 0 :(得分:369)

问题是在一个case中声明的变量在后续case中仍然可见,除非使用了明确的{ }块,但它们不会被初始化< / em>因为初始化代码属于另一个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;
}

答案 1 :(得分:61)

在case语句中声明新变量是导致问题的原因。在case中包含所有{}语句会将新声明的变量的范围限制为当前正在执行的解决问题的案例。

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

答案 2 :(得分:7)

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

JohannesD现在为标准做了解释。

C++11 N3337 standard draft 6.7&#34;声明声明&#34;表示:

  

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 past initialization

C99 N1256 standard draft附件I&#34;常见警告&#34;表示:

  

2具有自动存储持续时间的对象初始化的块跳转到

答案 3 :(得分:5)

JohannesD's answer是正确的,但我觉得在问题的某个方面并不完全清楚。

他给出的例子在案例1中声明并初始化变量i,然后在案例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 包子露宪 六四事件 法轮功 explained,我们根本无法跳转到case 2:,因为这会跳过i的初始化声明,并且尽管case 2根本没有使用i,但在C ++中仍然禁止这样做。

有趣的是,通过一些调整(#ifdef#include相应的标题,以及标签后面的分号,因为labels can only be followed by statements, and declarations do not count as statements in 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 ++没有编译器接受它。