Avoiding Global Variables

How would I fix my program to avoid my variables being global?
(Note: I took out the actual code for viewing simplicity.)

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
using namespace std;

float x, y, z;    // Global Variables

void FunctionOne()	
{
        Equation (Example: x = y + 1)
}
void FunctionTwo()	
{
	Equation
}
void FunctionThree()
{
	Equation  
}
void FunctionFour()	
{
	Equation 
}

int main()
{
	int input, repeat;

	do
		{
			cout << "1" << endl;
			cout << "2" << endl;
			cout << "3" << endl;
			cout << "4" << endl;
			cout << "5 Quit" << endl << endl;
			cout << "You Choose: " << endl;
		
			cin >> input;			

			switch (input)
				{
					case 1:			

                                        cin >> y;
                                        FunctionOne();
					break;

					case 2:			

					FunctionTwo();
					break;

					case 3:			
    
                                        FunctionThree();
				        break;
	
					case 4:			

					FunctionFour();
					break;

					case 5:			

					return 0;

					default:
		
					cout << "Error";
					break;

				}	
                        
                        cout << "Repeat? Enter 1";
			cin >> runAgain;
				
			if (repeat != 1)
				{
					return 0;
				}
	
		} while(repeat = 1);  
}	
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
float functionOne(float y)
{
    return y + 1;
}

/* [...] */

//...
    float x, y, z;
    switch (input) {
      case 1:
        std::cin >> y;
        x = functionOne(y);
//... 
You can pass arguments to functions by value and by reference, and return values from functions.
Topic archived. No new replies allowed.