c - Clarification on the use of fgetc -
this question has answer here:
there following code part of function have been given:
char ch; ch = fgetc(fp); if (ch == eof) return -1; where fp pointer-to-file/stream passed parameter function.
however, having checked usage of fgetc(),getc() , getchar(), seems return type int rather type char because eof not fit in values 0-255 used in char, , < 0 (e.g. -1). however, leads me ask 3 questions:
- if
getchar()returns int, whychar c; c = getchar();valid usage of function? c automatically type cast char in case, , in casegetchar()replacedgetc(fp)orfgetc(fp)? - what happen in program when
fgetc()or other 2 functions return eof? again try , cast char before fail? gets stored inch, if anything? - if eof not character, how
ch == eofvalid comparison, since eof cannot represented char variable?
if getchar() returns int, why char c; c = getchar(); valid usage of function?
it's not. because can write , compiler (somehow) allows compile it, not make code valid.
i believe above answers questions.
just add, in case eof returned, cannot stored in char. signedness of char implementation defined, thus, per chapter 6.3.1.3, c11
when value integer type converted integer type other _bool, if value can represented new type, unchanged.
otherwise, if new type unsigned, value converted repeatedly adding or subtracting 1 more maximum value can represented in new type until value in range of new type.60)
otherwise, new type signed , value cannot represented in it; either result implementation-defined or implementation-defined signal raised.
Comments
Post a Comment