我知道使用未初始化的变量是错误的,但问题出现在未初始化的整数的上下文中,在我稍后在代码中为其赋值之前我没有使用.
我应该期待得到奇怪的结果吗?或者这只是不好的做法?
我是一名新生计算机科学专业的学生,对任何错误都感到抱歉!
这没关系:
int i;
result = someFunc(&i);//it does not matter what value i is, it will
//be assigned in the function.
Run Code Online (Sandbox Code Playgroud)
在哪里someFunc()定义:
void someFunc(int *in)
{
*in = 10;
}
Run Code Online (Sandbox Code Playgroud)
这不好吗
int i;
int someArray[10];
int a = someArray[i];//it is not known what value 'i' is. Fault if > 9.
Run Code Online (Sandbox Code Playgroud)
但是,作为一个良好的编程习惯(可维护性,可读性,主动的bug预防),初始化是一个好主意:
int i = 0;
char *tok = NULL;
char string[] = {"string"};
float array[100] = {0};
... and so on.
Run Code Online (Sandbox Code Playgroud)