uninitialized local variable

1. why the local variable must have a value? although if it is global it works normally?
2. the last line before return 0 doesn't print the ch2 content but i tried to put endl it works, i see it should work without endl, why it doesn't print without endl;?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 int main()
{
	char ch; //this line give me error "uninitialized local variable" 
                     //but it works if i make it global
	std::string ch2;
 	std::cout << "please enter anything " << std::endl;
	while (ch != '\r')
	{
		ch=_getch();
		ch2 += ch;
		std::cout << "*";
	}
	std::cout << "\n you typed the following "<<ch2; //i must put endl to see the content
	return 0;
}
Last edited on
> 1. why the local variable must have a value? although if it is global it works normally?
Because as a global, you get a ch = 0; for free.

As a local, it means what it says.

> while (ch != '\r')
Now roll your 256-sided dice, and feel lucky if ch just happens to be '\r' before you get to read a character.

You can make the whole thing go away by just doing
char ch = '\0';


> //i must put endl to see the content
And?
So do it then.

> std::cout << "\n you typed the following "<<ch2;
Most normal people put the \n at the end of the line, not the start of the line.
You see, \n also has the magic property of also flushing the output stream so you can actually see it.


Last edited on
char ch; //this line give me error "uninitialized local variable"
this is not an 'error' it is a warning, which can be flagged as an error with a compiler setting (call warnings errors setting). It is fine, but best practice is to initialize variables, always, so it warns you.

2) if for some reason your setup is doing this and you do not want any kind of end of line, you can do cout.flush() instead. This happens rarely for me; seems like most of the time it prints without this extra step and once in a while it decided it has to be there. Compilers can be a little inconsistent here.
Last edited on
"salem c", "jonnin" thank you guys for your support
cheers.
Topic archived. No new replies allowed.