Thor
Thor

Reputation: 10038

Why int ia2[10] has a default value of 0 even though it is defined inside a function?

I'm new to C++ and is trying to learn the concept of arrays. I saw the code and statement below from C++ primer.

As with variables of built-in type, a default-initialized array of built-in type that is defined inside a function will have undefined values.

Judging from this statement, the int ia2[10] below is define inside the int main(){} function and therefore should not have default value and all its elements should be undefined. However, when I tried to print out their value, they are all equal to 0, which is the default value for any uninitialised int array.

Why is this happening?

int main() {
    string sa2[10]; //all elements are empty strings
    int ia2[10]; //all elements are undefined

    for (int i = 0; i < 10; i++){
        cout << "sa2[" << i << "] " << sa2[i] << endl;
        cout << "ia2[" << i << "] " << ia2[i] << endl;
    }
}

Output:

sa2[0] 
ia2[0] 0
sa2[1] 
ia2[1] 0
sa2[2] 
ia2[2] 0
sa2[3] 
ia2[3] 0
sa2[4] 
ia2[4] 0
sa2[5] 
ia2[5] 0
sa2[6] 
ia2[6] 0
sa2[7] 
ia2[7] 0
sa2[8] 
ia2[8] 0
sa2[9] 
ia2[9] 0

Upvotes: 0

Views: 75

Answers (1)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

It isn't forced to have some random value. It's undefined what value will be there, so it could be anything, including all zeroed out. Also note that reading the value is undefined behavior.

Upvotes: 1

Related Questions