Variable initialization question

Getting straight to it, how do I know when I need to initialize a variable in the declaration line?

Ex:
The program below prompts the user for an integer, reads it and then prints out all of the prime numbers between 3 and the number entered. The declared variables are 'number', 'x', 'y', 'm' and 'n'. I know that the variables 'm' and 'n' are initialized at the beginning of the for loops. What I currently think is going on is that I don't need to initialize 'number' because it's being initialized at the cin statement. Is this right? I sort of understand why I need to initialize 'y' to zero (to make the program work properly. Another int will compile and run, but have incorrect output), but what I don't understand is why I don't need to initialized the x variable. The program compiles and runs fine without it, but if I don't initialize y I get a Break error stating that y is not initialized.

Thanks in advance...

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
//Program to read an integer that is greater than 2, then finds
//and prints all of the prime numbers between 3 and the number
//entered.

#include <iostream>
using namespace std;

int main()
{
	int number, x, y (0);
	cout << "Enter a number and the program will list all prime numbers below it: ";
	cin >> number;

	for (int n = 3; n <= number; n++)
	{
		for (int m = 2; m <= n; m++)
		{
			x = n % m;
			if (x == 0)
				y++;
		}
		if (y == 1)
			cout << n << " is a prime number." << endl;
		else
			y = 0;
	}
	
	system("pause");
	return 0;
}
If you do not initalize a value for a variable it will have the value last kept in memory. So say you do something like

1
2
3
int number;

cout << "Number + 1 = " << number + 1 << endl;


What will the output be? We do not know what number is by default they are not initalized to 0. So you should initalize it in this case.


Also cin does not initalize the variable number. It assign a value to the uninitialized variable. You were not directly modifying the old value but instead assigning a new value so that is fine. But in the earlier example we were trying to directly modify the old value which was undefined.


http://v2.cplusplus.com/forum/general/62807/
Thank you, that helps!

Also, one more question and something that I just noticed;

Do I not get an error stating that x is not initialized because is being set equal to quotient of two variables (m & n) that are initialized to 2 and 3, respectively? (ie: x = n % m)?
Also, I did read that thread before, but was having a hard time understanding it. Will give it another read through.
In your code you are assigning the value of n % m to x before using it. That's why the program runs fine because there's already a value in x when you compare it to 0.

Note: That wouldn't have been possible if you hadn't previously assigned values to both n and m.
Topic archived. No new replies allowed.