在下面的 C 代码中(受 K&R 中的示例启发),变量 nw
被视为未初始化:
#include <stdio.h>
#define IN 1
#define OUT 0
main(){
int c,nl,nw,nc = 0;
int state = OUT;
while((c=getchar())!=EOF){
++nc;
if(c=='\n')
++nl;
if(c==' ' || c=='\n' || c=='\t')
state = OUT;
else if(state == OUT){
state = IN;
++nw;
}
}
printf( "%d %d %d\n" , nl, nw, nc);
}
例如:
input: one two three
output: 1 796411731 14
中间的数字应该是3(nw
= 字数)
我不明白为什么会这样,因为我一开始就明确地为它分配了一个值。
最佳答案
I don't understand why this happens, given that I explicitly assign a value to it in the beginning.
您没有将值分配给 nw
:nc
是唯一分配的值。
与数组初始化不同,在数组初始化中您可以通过从初始化程序中省略它们来将零分配给多个元素,标量变量必须全部单独初始化:
int c, nl = 0, nw = 0, nc = 0;
请注意,您不需要初始化c
,因为它是在循环头中无条件赋值的。
关于c - 变量被视为未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25690633/