为什么我们必须在使用前初始化变量? [英] Why we must initialize a variable before using it?

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value\">What发生在C中声明,未初始化的变量?它有一个价值?

现在我读自学℃下21天。在第三章中,有一注是这样的:

Now I'm reading Teach Yourself C in 21 Days. In chapter 3, there is a note like this:

请勿使用尚未初始化的变量。结果可以
  未predictable。

DON'T use a variable that hasn't been initialized. Results can be unpredictable.

请给我解释一下为什么是这样的情况。这本书提供了有关它没有进一步的澄清。

Please explain to me why this is the case. The book provide no further clarification about it.

推荐答案

在声明一个变量,它会指向一块内存。

When a variable is declared, it will point to a piece of memory.

访问变量的值,会给你一块内存中的内容。

Accessing the value of the variable will give you the contents of that piece of memory.

然而,直到变量被初始化,即一块内存可以包含任何内容。这就是为什么使用它是联合国predictable。

However until the variable is initialised, that piece of memory could contain anything. This is why using it is unpredictable.

其他语言可以帮助您在这个领域,当你给它们自动初始化变量,但作为一个C程序员,你用,让你想与你的程序做任何假设一个相当低级的语言工作。你作为程序员必须明确地告诉程序做的一切。

Other languages may assist you in this area by initialising variables automatically when you assign them, but as a C programmer you are working with a fairly low-level language that makes no assumptions about what you want to do with your program. You as the programmer must explicitly tell the program to do everything.

这意味着初始化变量,但它也意味着更多之外。例如,在C,你必须非常小心,你去分配您分配,一旦你与他们完成的任何资源。其他语言会自动清理后程序完成时;但在C,如果你忘了,你会刚刚结束了内存泄漏。

This means initialising variables, but it also means a lot more besides. For example, in C you need to be very careful that you de-allocate any resources that you allocate once you're finished with them. Other languages will automatically clean up after you when the program finished; but in C if you forget, you'll just end up with memory leaks.

ç会让你得到做很多事情,这将是在其他语言困难或不可能。但是,这种权力也意味着,你必须要对你想当然的其它语言的内务处理任务的责任。

C will let you get do a lot of things that would be difficult or impossible in other languages. But this power also means that you have to take responsibility for the housekeeping tasks that you take for granted in those other languages.

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

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