-1

我编译了这个(gcc编译器):

#include< stdio.h>

 main() {

    unsigned char ch;
    FILE *fp;
    fp=fopen("trial","r");
    while((ch=getc(fp))!=EOF)
        printf("%c",ch);
    fclose(fp);
}

它给出了以下内容:

Warning: comparison is always true due to limited range of the data type

执行时,终端上会打印出无穷无尽的字符流。(假设我在编译程序之前创建了一个名为“trial”的文件并在文件中写入了一些文本。)

请解释警告......

4

4 回答 4

1

因为 EOF 是 -1 而你ch是 unsigned char 这意味着 ch 永远不会变成 -1。

而是使用int ch;

于 2012-04-07T16:37:08.370 回答
0

getc()返回一个int. 您正在使用该分配将其截断(并更改签名)unsigned char,因此它永远不会匹配EOF. 只需将类型更改为ch即可int

于 2012-04-07T16:36:08.927 回答
0

getc有充分的理由返回一个整数。EOF 指示符超出了普通字符的范围,否则您可能会将合法字符与 EOF 指示符混淆。但是,您将结果分配给将答案限制在char值范围内的字符。简而言之,您永远不会知道何时以这种方式到达文件末尾。在将其与 EOF 进行比较,将“ch”设为int类型或将调用结果分配给getc类型unsigned char

于 2012-04-07T16:37:19.273 回答
0

The EOF value in C is an int while ch here is a char. The char type is smaller than int and hence can represent less values than int can. EOF is one of the values which char simply can't ever represent and hence ch will never be equal to EOF.

In this scenario getc actually returns an int so it can represent EOF. But you are immediately shrinking it to a char and losing that extra information.

Here's a way to properly write this.

int cur;
FILE *fp;
fp=fopen("trial","r");
while((cur = getc(fp))!=EOF) {
  unsigned char ch = cur;
  printf("%c",ch);
}
fclose(fp);
于 2012-04-07T16:40:47.893 回答