如何解决此错误:跳转到case标签交叉初始化
How do I resolve this error: jump to case label crosses initialization
我的计算器代码中有以下错误,不知道如何纠正它。请给我一些建议。
错误:错误:跳转到大小写标签[-fpermissive]|错误:交叉初始化'int sum'|错误:'exit'未在此范围内声明|
代码:#include <iostream>
#include <cmath>
using namespace std;
void display_menu();
int get_menu_choice();
void get_two_numbers(int &a, int &b);
int add(int a, int b);
int subtract(int a, int b);
int main()
{
int choice;
do
{
display_menu();
choice = get_menu_choice();
int x, y;
switch (choice)
{
case 1: get_two_numbers(x, y);
int sum = add(x, y);
cout << x << " + " << y << " = " << sum << endl;
break;
case 2: get_two_numbers(x, y);
int diff = subtract(x, y);
cout << x << " - " << y << " = " << diff << endl;
break;
default:;
}
} while (choice != 3);
cout << "Good bye...now." << endl;
return 0;
}
void display_menu()
{
cout << endl;
cout << "Simple Calculator Menu" << endl;
cout << "----------------------" << endl;
cout << " 1. Addition (+) " << endl;
cout << " 2. Subtraction (-) " << endl;
cout << " 3. Quit to exit the program" << endl;
cout << endl;
}
int get_menu_choice()
{
int choice;
cout << "Enter your selection (1, 2, or 3): ";
cin >> choice;
while(((choice < 1) || (choice > 3)) && (!cin.fail()))
{
cout << "Try again (1, 2, or 3): ";
cin >> choice;
}
if (cin.fail())
{
cout << "Error: exiting now ... " << endl;
exit(1);
}
return choice;
}
void get_two_numbers(int &a, int &b)
{
cout << "Enter two integer numbers: ";
cin >> a >> b;
}
int add(int a, int b)
{
return (a + b);
}
int subtract(int a, int b)
{
return (a - b);
}
在case语句中声明新变量而不创建封闭作用域:
switch (choice)
{
case 1: get_two_numbers(x, y);
//* vv here vv *
int sum = add(x, y);
//* ^^ here ^^ */
cout << x << " + " << y << " = " << sum << endl;
break;
case 2: get_two_numbers(x, y);
//* vv here vv */
int diff = subtract(x, y);
//* ^^ here ^^ */
cout << x << " - " << y << " = " << diff << endl;
break;
default:;
}
修复方法:
switch (choice)
{
case 1:
{
get_two_numbers(x, y);
int sum = add(x, y);
cout << x << " + " << y << " = " << sum << endl;
}
break;
case 2:
{
get_two_numbers(x, y);
int diff = subtract(x, y);
cout << x << " - " << y << " = " << diff << endl;
}
break;
default:
break;
}
当然,括号和缩进的确切格式取决于您。
开关的"case"不创建作用域,因此,正如错误提示的那样,如果选项不为1,则跳过了"sum"的初始化。
你需要在switch之外声明sum和diff,或者为每种情况创建{}块
应该在switch语句之外而不是在case中声明变量。特别是sum
和diff
在您的代码中有问题。在switch语句之外初始化这些变量之后,您就可以设置它们的值了。
相关文章:
- C 和 C++ 中开关语句的案例标签的常量值,但显示不同的行为
- 如何正确指定 goto 语句的标签?
- 使用g++静态初始化带有命名标签的嵌套C++结构
- 通过水平滚动条更改标签
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 从 QFontDatabase 设置 QFont 将所有标签设置为等宽字体?Qt C++
- 在C++中存储要输入的标签列表
- 如何在等效列表中查找最小的连接标签
- 标签检测鼠标单击 c++
- 无法将行编辑中的文本打印到 Qt C++ 中的标签
- 如何根据C++中的标签运行特定函数?
- C++ Expat 仅打印元素的第一个字母和标签中的数据
- 默认标签显然在 switch 语句中不起作用
- 在 gcc/clang (C++) 中获取函数范围之外的标签地址
- 在"printf"中使用标签"h"或"hh"是否涉及未定义的
- GTK 3 C++按钮中带有标签的图标
- 如何使QLineSeries/QXYSeries仅显示一个点标签
- 为什么case语句中的标签应该是常量
- 如何解决此错误:跳转到case标签交叉初始化
- 'element'的初始化被'case'标签跳过