What is the value compared in the following code?
while ((c = getchar()) != EOF)
if ( c == '\n')
I know that '\n' is a constant variable because of the single quote. I know that it represents the numerical value of the character on the ASCII table, right? That is equal to 110. But what does
((c = getchar()) != EOF) return?
Thanks
The crucial point is that
cmust be anint:It is assumed that an
intcan hold more values than achar, or at least more values that the system’s narrow multibyte encoding uses*, andgetcharreturns a special constantEOFwhen there it failed to read more data. Otherwise, it is guaranteed that you can convertcto acharand obtain the value of the character that was read.It is a common mistake to declare
citself as achar, in which case the loop might never terminate, since you might not be able to capture the special valueEOF, or otherwise there would be a perfectly valid character which would be indistinguishable from(char)EOF.*) For example, it would be perfectly fine if both a
charand anintwere 32 bits wide on a given platform, as long as, say, the narrow stream could only return units with values in the range [-128, 128), and you could use-200asEOF.