在 C 中初始化变量 [英] Initializing variables in C
问题描述
我知道有时候如果你不初始化一个int
,你打印整数就会得到一个随机数.
I know that sometimes if you don't initialize an int
, you will get a random number if you print the integer.
但是将所有内容初始化为零似乎有点愚蠢.
But initializing everything to zero seems kind of silly.
我问是因为我正在评论我的 C 项目,而且我对缩进非常直接,它可以完全编译(90/90,谢谢 Stackoverflow),但我想在样式点上获得 10/10.
I ask because I'm commenting up my C project and I'm pretty straight on the indenting and it compiles fully (90/90 thank you Stackoverflow) but I want to get 10/10 on the style points.
那么,问题来了:什么时候适合初始化,什么时候应该声明一个变量:
So, the question: when is it appropriate to initialize, and when should you just declare a variable:
int a = 0;
对比
int a;
推荐答案
一个还没有被提及的规则是:当变量在函数内部声明时它没有被初始化,而当它在静态或全局范围设置为 0:
A rule that hasn't been mentioned yet is this: when the variable is declared inside a function it is not initialised, and when it is declared in static or global scope it's set to 0:
int a; // is set to 0
void foo() {
int b; // set to whatever happens to be in memory there
}
但是 - 为了便于阅读,我通常会在声明时初始化所有内容.
However - for readability I would usually initialise everything at declaration time.
如果您有兴趣详细了解此类内容,我会推荐 此演示文稿 和这本书
If you're interested in learning this sort of thing in detail, I'd recommend this presentation and this book
这篇关于在 C 中初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!