英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论