Unexpected results when assigning calculated value to variable

Hi,

I've been following a C++ tutorial, and I always try to play around with each one to get a better understanding. This program just takes a set of numbers and calculates the average. When I perform the calculation in a cout statement, I get the results I expect, however if I assign the calculation to a variable I get some extremely strange results. I have no idea why.

Program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    int age;
    int ageTotal = 0;
    int numberOfPeople;
    
    cout << "Enter an age, or enter -1 to quit: ";
    cin >> age;
    
    while (age != -1) {
        ageTotal = ageTotal + age;
        numberOfPeople++;
        
        cout << "Enter an age, or enter -1 to quit: ";
        cin >> age;
    }
    
    cout << "Number of people entered: " << numberOfPeople << endl;
    cout << "The average age is: " << ageTotal / numberOfPeople;
    
    // If I add this code, I get unexpected results
    //int average = 0;
    //average = ageTotal / numberOfPeople;
    //cout << "Variable average is: " << average; 

Results without assigning average to variable:
1
2
3
4
5
 Enter first persons age or -1 to quit: 10
 Enter next persons age, or -1 to quit: 10
 Enter next persons age, or -1 to quit: -1
 Number of people entered: 2
 The average age of people entered is: 10

Results when I do assign the average to variable:
1
2
3
4
5
6
50 Enter first persons age or -1 to quit: 10
 51 Enter next persons age, or -1 to quit: 10
 52 Enter next persons age, or -1 to quit: -1
 53 Number of people entered: 4197138
 54 The average age of people entered is: 0
 55 Variable average is: 0

Why is this???
You never assign any particular value to numberOfPeople before line 10, so its value is undefined. Undefined incremented is still undefined.
@helios, thank you so much. Defining it did fix the problem.

I still don't totally understand why though. If an uninitialized incremented variable is undefined, then why does it return the expected values on lines 16 and 17? Does C++ store variable values in a stack like Java? Is it that it's referencing the value in the stack, but hasn't been assigned a space in memory?

Thanks so much for any info.
then why does it return the expected values on lines 16 and 17?
An undefined value is undefined. There's no point in trying to derive meaning from it.

Does C++ store variable values in a stack like Java?
C++ stores some things on the stack, but not quite the same way Java does it.

Is it that it's referencing the value in the stack, but hasn't been assigned a space in memory?
No. The variable is stored on the stack. The stack is the place where its memory was allocated. It's just that the value hasn't been initialized.
@helios thanks again, I appreciate the help!
Topic archived. No new replies allowed.