在C编程语言中,应在将变量赋值之前声明变量。
例如:
// declaration of variable a and
// initializing it with 0.
int a = 0;
// declaring array arr and initializing
// all the values of arr as 0.
int arr[5] = {0};
但是,甚至可以在不声明变量的情况下为变量分配0或1。让我们看一个例子,看看如何完成它:
#include
#include
// implicit initialization of variables
a, b, arr[3];
// value of i is initialized to 1
int main(i)
{
printf("a = %d, b = %d\n\n", a, b);
printf("arr[0] = %d, \narr[1] = %d, \narr[2] = %d,"
"\n\n", arr[0], arr[1], arr[2]);
printf("i = %d\n", i);
return 0;
}
输出:
a = 0, b = 0
arr[0] = 0,
arr[1] = 0,
arr[2] = 0,
i = 1
在数组中,如果使用的元素少于数组的指定大小,则默认情况下其余元素将设置为0。
让我们看另一个例子来说明这一点。
#include
#include
int main()
{
// size of the array is 5, but only array[0],
// array[1] and array[2] are initialized
int arr[5] = { 1, 2, 3 };
// printing all the elements of the array
int i;
for (i = 0; i < 5; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
输出:
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 0
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。