Question about global variable in recursive function

Hi everyone,

I don't quite understand the difference in output for the following program when I declare "char ch" as a global / local variable:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//purpose: to reverse the order of a word or a sentence. eg) program -> margorp.
 #include <iostream>
using namespace std;
void msg()
{
	char ch;
	cin.get(ch);	    
	if (ch != '.')      
	{                   
		msg();
	}
        cout << ch;
}

int main()
{
	msg();	
	
	system ("pause");
	return 0;
}


as you can see if I declare the variable (ch) as global, the program will output dots (.) corresponding to how many characters that I've inputted.

eg) if I enter abcd, the output would be: ....

But how is this possible?

thank you all for the insights.
Last edited on
If ch is global it contains the very last input character which is the dot, otherwise you won't see any output.
if ch is local it is pushed/popped to/from the stack each time msg() is called.
Topic archived. No new replies allowed.