Practice mode C Language

Why should the return value of getchar() be stored in an int rather than a char?

Correct answer B. So that EOF, a negative int, can be told apart from every valid character

Explanation

getchar returns each character as an unsigned char converted to int, or the macro EOF, which is a negative int. Storing the result in a char squeezes 257 possible values into 256, so either a valid byte such as 0xFF is mistaken for EOF or, where char is unsigned, EOF is never detected and the loop runs forever. An int keeps them distinct.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.