-2
#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

Asif_102
  • 53
  • 5
  • 1
    Global means outside the function, local means inside the function – Solomon Ucko Feb 15 '23 at 19:51
  • 3
    _@asif_ _" I have seen many declare arrays globally in their code"_ Don't adopt that behavior please, it lowers your chances for serious learning of the language, and getting a good job at the software development industry a lot. – πάντα ῥεῖ Feb 15 '23 at 20:22
  • Note that you can write `int a[100] {};` anywhere, and it will always be cleared. Why bother with the other rukes? – BoP Feb 15 '23 at 22:16
  • *In competitive programming I have seen many declare arrays globally in their code* -- I've also seen many declare arrays of one million elements, just because the question states there could be up to a million elements. If you show up at an interview writing code like that, I can bet you will not be hired. – PaulMcKenzie Feb 15 '23 at 22:47

1 Answers1

3

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770