Asif_102
Asif_102

Reputation: 53

c++ initial value of global array declarer vs initial value of local function array declarer

#include <bits/stdc++.h>
using namespace std;

int a[100]; // <--

int main() {
    
    for (int i = 0; i < 100; i++) {
        cout << a[i] << " ";
    }
    
    return 0;
}

After declaring the array globally in the above code, all the indices get the value 0. What is the reason for this?

#include <bits/stdc++.h>
using namespace std;

int main() {

    int a[100]; // <--

    for (int i = 0; i < 100; i++) {
        cout << a[i] << " ";
    }

    return 0;
}

After declaring the array inside the main function in the above code and printing the values of all the indices of the array, the garbage values at all the indices are found.

In competitive programming I have seen many declare arrays globally in their code. But I don't understand the exact reason

Upvotes: -2

Views: 174

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597941

If a variable declaration does not have an explicit initializer specified, and is not (part of) a class/struct type whose constructor initializes its data, then the variable gets default-initialized to zeros at compile-time only when it is declared in global or static scope, whereas it is not default-initialized to anything at all when declared in local scope.

Upvotes: 3

Related Questions