Integer value is lost in another function

Aug 12, 2014 at 10:57pm
I'm having trouble with this basic program. I'm 100% lost when it comes to this, I have written much more complex programs...solving Sudoku Puzzles and such, I however have taken a break from coding and am working on learning Object Oriented programming.

Everything functions properly, however the Do-While loop continues forever because INT key does not equal 3 in this function, when i print the value of key in that function it shows up completely random like (170,000 + 900,000)I'm assuming these are memory values. This is a basic assignment from my old textbook, the idea is to not modify the function main. All of my #includes are correct but are in a header file.

I'm not really sure what's wrong?
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

int getKey(int key);
bool keyCorrect(int key);
int convert(char message[], int key);
void display(char message[]);

using namespace std;

int main()
{
	int key = 0;
	char message[] = " Vhfuhw";


	do
		getKey(key);
	while (!keyCorrect(key));

	convert(message, key);

	display(message);
}

int getKey(int key)
{
	cout << "Please enter the key to decrypt the message: ";
	cin >> key;
	return key;
}

bool keyCorrect(int key)
{
	int correct = 3;
	if (key == correct)
	{
		return true;
	}
	else
	cout << "Incorrect! Try again" << endl;
	return false;
}

int convert(char message[], int key)
{
	int c;
	for (c = 0; message[c] != 0; c++)
	{
		message[c] = message[c] - 3;
	}
	return c;
}

void display(char message[])
{
	int d;
	cout << "The translated message is: \"";
	for (d = 0; message[d] != 0; d++)
	{
		cout << message[d];
	}
	cout << "\"" << endl;
}
Aug 12, 2014 at 11:09pm
see if this helps
1
2
3
4
5
6
	
do
{
     key = getKey(key);

}while (!keyCorrect(key));
Last edited on Aug 12, 2014 at 11:09pm
Aug 13, 2014 at 2:03pm
Thank you, that does fix the problem.

Is there any particular reason why?
Aug 13, 2014 at 2:54pm
By default, C++ parameters are "pass by value." This means that the key variable in main and the key variable in getKey are completely different variables. Although you return the updated key value at line 28, the code at line 16 doesn't do anything with it.

Yanson's change assigns the return value from getKey() back to main's key variable.
Topic archived. No new replies allowed.