Home>
Reasons to declare an array globally

I am doing competitive programming using C ++, but I think that many people declare arrays globally.

If i use it in some functions, you can understand that intention,
I often see it declared globally, even though it's only used in the main function.

Example: Problems with dynamic programming Declaring an array globally

The specific content of the main function is not directly related to this question.

#include<bits/stdc ++. H>
using namespace std;
using ll = long long;
template<class T>inline bool chmax (T&a, T b) {if (a<b) {a = b;return true;} return false;}
template<class T>inline bool chmin (T&a, T b) {if (a>b) {a = b;return true;} return false;}
// Input
int N;
long long a [100010] [3];// Declare the array globally
// DP table globally declared
long long dp [100010] [3];
int main () {
    int N;cin >>N;
    for (int i = 0;i<N;++ i) for (int j = 0;j<3;++ j) cin >>a [i] [j];
    // loop
    for (int i = 0;i<N;++ i) {
        for (int j = 0;j<3;++ j) {
            for (int k = 0;k<3;++ k) {
                if (j == k) continue;
                chmax (dp [i + 1] [k], dp [i] [j] + a [i] [k]);
            }
        }
    }
    long long res = 0;
    for (int j = 0;j<3;++ j) chmax (res, dp [N] [j]);
    cout<<res<<endl;
}
Question

Considering the above example, I would like to know the merits and reasons for declaring an array globally.
If anyone knows, please.

  • Answer # 1

    Generally, if you define it as a local variable, that area is taken up by the stack area.
    However, the stack area can only take a few megabytes to a few tens of megabytes at most.
    If you try to allocate such a large array area on the stack, it will eat up the stack and it will not work properly.

  • Answer # 2

    That's because I don't want to spend time on unrequested parts (such as dynamically allocating memory) in order to get the desired results in a limited amount of time, so what is the code to maintain for a long time? Will change.

  • Answer # 3

    Since it is competitive programming, I think it has a lot of time constraints.
    If you define it in the data area, you don't have to worry about stack consumption.
    Also, with dynamic allocation, there is no need to write code to assign.
    Isn't it an implementation that prioritizes time?