C中int数组的初始值-为什么? [英] Initial value of int array in C - why?

查看:82
本文介绍了C中int数组的初始值-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么值

int array[10];

在函数中声明时未定义,并且在声明为 static 时被 0 初始化?

undefined when declared in a function and is 0-initialized when declared as static?

我一直在阅读这个问题的答案很明显

函数中的

[表达式 int array [10]; ]意味着:无需进行任何初始化即可获取10 int大小的内存区域的所有权.如果将数组声明为全局1或函数中的静态,则所有尚未初始化的元素都将初始化为零.

[the expression int array[10];] in a function means: take the ownership of 10-int-size area of memory without doing any initialization. If the array is declared as a global one or as static in a function, then all elements are initialized to zero if they aren't initialized already.

问题:为什么这种行为?编译器程序员是否会决定(出于特定原因)?使用的特定编译器可以做些不同的事情吗?

Question: why this behaviour? Do the compiler programmers decide that (for a particular reason)? Can a particular compiler used do the things differently?

为什么要问这个问题:之所以问这个问题,是因为我想使我的代码可在体系结构/编译器之间移植.为了确保它,我知道我总是可以初始化声明的数组.但是,这意味着我只会为此操作浪费宝贵的时间.那么,哪个是正确的决定?

Why I am asking this: I am asking this question because I would like to make my code portable among architectures/compilers. In order to ensure it, I know I can always initialize the declared array. But this means that I will lose precious time only for this operation. So, which is the right decision?

推荐答案

自动 int数组[10]; 不会隐式归零,因为归零需要时间,您可能不需要将其归零.此外,您不仅要付出一次代价,而且每次控件超出初始化变量时都要付出代价.

An automatic int array[10]; isn't implicitly zeroed because the zeroing takes time and you might not need it zeroed. Additionally, you'd pay the cost not just once but each time control ran past the initialized variable.

静态/全局 int数组[10]; 隐式归零,因为静态/全局变量是在加载时分配的.内存将从OS刷新,并且如果OS完全具有安全意识,则内存将已经被清零.否则,加载代码(操作系统或动态链接器)将必须将它们归零(因为C标准需要它),但是对于所有全局变量/,它应该能够通过一次调用 memset 来做到这一点/静态,比一次将每个静态/全局变量清零要有效得多.

A static/global int array[10]; is implicitly zeroed because statics/globals are allocated at load time. The memory will be fresh from the OS and if the OS is security conscious at all, the memory will have been zeroed already. Otherwise the loading code (the OS or a dynamic linker) will have to zero them (because the C standard requires it), but it should be able to do it in one call to memset for all globals/statics, which is considerably more efficient than zeroing each static/global variable at a time.

此初始化完成一次.即使函数内部的 static s仅有一次初始化,即使它们具有非零初始化程序(例如, static int x = 42; .)这就是为什么C要求C的初始化程序静态是常量表达式.

This initialization is done once. Even statics inside of functions are initialized just once, even if they have nonzero initializers (e.g., static int x = 42;. This is why C requires that the initializer of a static be a constant expression).

由于所有全局变量/静态变量的加载时间清零是OS保证的或可以有效实施的,因此它也可能是标准保证的,从而使程序员的生活更轻松.

Since the loadtime zeroing of all globals/statics is either OS-guaranteed or efficiently implementable, it might as well be standard-guaranteed and thereby make programmers' lives easier.

这篇关于C中int数组的初始值-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆