我编写了一个涉及使用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;
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*esD 403
问题是在一个case中声明的变量在后续的cases 中仍然可见,除非使用了显式{ }块,但它们不会被初始化,因为初始化代码属于另一个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!
}
Run Code Online (Sandbox Code Playgroud)
在显式块中包装案例可以解决问题:
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
}
Run Code Online (Sandbox Code Playgroud)
为了进一步阐述,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;
}
Run Code Online (Sandbox Code Playgroud)
Mah*_*esh 66
在case语句中声明新变量是导致问题的原因.将所有case语句括起来{}会将新声明的变量的范围限制为当前正在执行的解决问题的情况.
switch(choice)
{
case 1: {
// .......
}break;
case 2: {
// .......
}break;
case 3: {
// .......
}break;
}
Run Code Online (Sandbox Code Playgroud)
跳过一些初始化的C++ 11标准
JohannesD现在就标准做了解释.
在C++ 11 N3337标准草案 6.7"宣言声明"说:
3可以转换为块,但不能以初始化方式绕过声明.从具有自动存储持续时间的变量不在其范围内的点跳转到(87)的程序是不正确的,除非该变量具有标量类型,具有普通默认构造函数的类类型和一个普通的析构函数,这些类型之一的cv限定版本,或者前面类型之一的数组,并且在没有初始值设定项的情况下声明(8.5).
87)从switch语句的条件转移到case标签被认为是这方面的一个跳跃.
[例如:
Run Code Online (Sandbox Code Playgroud)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跳转到具有自动存储持续时间的对象初始化的块
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;
}
Run Code Online (Sandbox Code Playgroud)
人们可以期待这一计划被编译,因为都i和j仅仅是声明它们的案件中使用。不幸的是,它在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;
}
}
Run Code Online (Sandbox Code Playgroud)
感谢像http://rextester.com这样的在线编译器,您可以使用MSVC,GCC或Clang快速尝试将其编译为C或C ++。由于C始终有效(只需记住设置STDIN!),因为C ++没有编译器接受它。