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:

  1. if getchar() returns int, why char c; c = getchar(); valid usage of function? c automatically type cast char in case, , in case getchar() replaced getc(fp) or fgetc(fp)?
  2. what happen in program when fgetc() or other 2 functions return eof? again try , cast char before fail? gets stored in ch, if anything?
  3. if eof not character, how ch == eof valid 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

  1. when value integer type converted integer type other _bool, if value can represented new type, unchanged.

  2. 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)

  3. otherwise, new type signed , value cannot represented in it; either result implementation-defined or implementation-defined signal raised.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -