C++全局数组声明的初始值与局部函数数组声明的初始值

huangapple go评论62阅读模式
英文:

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;
}

在上面的代码中,全局声明数组后,所有的索引都被赋予值 0

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

int main() {

    int a[100]; // <--在主函数内声明

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

    return 0;
}

在上面的代码中,在主函数内声明数组并打印所有索引的值,所有索引都包含垃圾值

在竞赛编程中,我看到许多人在他们的代码中全局声明数组。但我不理解确切的原因。

英文:
#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

答案1

得分: 3

如果变量声明没有明确指定初始值,并且不是一个初始化其数据的class/struct类型的一部分,那么只有当它在全局或静态范围内声明时,该变量才会在编译时默认初始化为零,而在局部范围内声明时,它根本不会默认初始化为任何值。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月16日 03:48:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定