Calculator Code Error

I am receiving the following error and need assistance in correcting my code.
ERROR:

error: jump to case label [-fpermissive]|
error: crosses initialization of 'int diff'|
error: crosses initialization of 'int sum'|

CODE:

#include <iostream>
#include <cmath>
using namespace std;

// display the calculator menu
// Simple Calculator Menu
// ----------------------
// 1. Addition (+)
// 2. Subtraction (-)
// 3. Quit to exit the program
void display_menu();

// function get_choice reads, validates and returns
// the user's choice
int get_menu_choice();

// function gets two integer numbers typed by the user
// function reads the two numbers into a and b which are
// passed by reference
void get_two_numbers(int &a, int &b);

// function add returns a + b
int add(int a, int b);

// function substract returns a - 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);
}

Dont declare the variables inside your case statements - declare them at the top.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int main()
{
	int choice;
	int sum, diff;
	do
	{
		display_menu();
		choice = get_menu_choice();
		int x, y;
		switch (choice)
		{
		case 1: get_two_numbers(x, y);
			sum = add(x, y);
			cout << x << " + " << y << " = " << sum << endl;
			break;
		case 2: get_two_numbers(x, y);
			diff = subtract(x, y);
			cout << x << " - " << y << " = " << diff << endl;
			break;
		default:;
		}

	} while (choice != 3);

	cout << "Good bye...now." << endl;

	return 0;
}
Last edited on
Topic archived. No new replies allowed.