用C初始化变量 [英] Initializing variables in C

查看:109
本文介绍了用C初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是一个一般性的问题,对不起,如果这是不恰当的,因为我知道这是一个具体的问题和答案的网站,但我认为,因为这是学习的好有具体的答案尽可能的。

Just a general question, sorry if this is inappropriate because I know this is a specific question and answer website, but I think since this is for learning its good to have as specific of an answer as possible.

我知道有时候,如果你不初始化一个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项目,我直是pretty的缩进,它完全编译(90/90谢谢#1),但我想要得到的样式点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;

VS。

    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.

如果您有兴趣学习这种细节的东西,我建议你这个presentation 这本书

If you're interested in learning this sort of thing in detail, I'd recommend this presentation and this book

这篇关于用C初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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