初始化变量 [英] Initialize a variable
问题描述
是更好当变量声明为初始化变量,或者只声明变量和使用变量?
什么是尤为明显,什么是更有效?
Is it better to initialize a variable when the variable is declared, or only declare the variable and use the variable? What is the beter, what is more efficient?
例如,我有这样的code:
For example, I have this code:
#include <stdio.h>
int main()
{
int number = 0;
printf("Enter with a number: ");
scanf("%d", &number);
if(number < 0)
number= -number;
printf("The modulo is: %d\n", number);
return 0;
}
如果我不初始化数量
中,code工作正常,但我想知道,是不是更快,更好,更fficient?它的好处是初始化变量?
If I do not initialize number
, the code works fine, but I want to know, is it faster, better, more fficient? Is it good to initialize the variable?
推荐答案
scanf函数
可能会失败,在这种情况下没有被写入号
。所以,如果你希望你的code是的正确的你需要初始化(或检查返回值 scanf函数
)。
scanf
can fail, in which case nothing is written to number
. So if you want your code to be correct you need to initialize it (or check the return value of scanf
).
不正确code的速度通常无关紧要,但对你比如code如果在速度上的差异在所有的话,我怀疑你将永远是能够测量它。设置一个 INT
0比I / O快得多。
The speed of incorrect code is usually irrelevant, but for you example code if there is a difference in speed at all then I doubt you would ever be able to measure it. Setting an int
to 0 is much faster than I/O.
这篇关于初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!