I compiled this (gcc compiler) :
#include< stdio.h>
main() {
unsigned char ch;
FILE *fp;
fp=fopen("trial","r");
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
It gives the follwing:
Warning: comparison is always true due to limited range of the data type
On executing, an endless stream of characters is printed on terminal.
(Assuming I created a file named “trial” before compiling the program and wrote some text in the file.)
Kindly explain the warning…..
The
EOFvalue in C is anintwhilechhere is achar. Thechartype is smaller thanintand hence can represent less values thanintcan.EOFis one of the values whichcharsimply can’t ever represent and hencechwill never be equal toEOF.In this scenario
getcactually returns anintso it can representEOF. But you are immediately shrinking it to acharand losing that extra information.Here’s a way to properly write this.