Why do we use int rather than char

Go to my personal blog

There is a program to copy input to output as blow.

#include <stdio.h>/* copy input to output */int main(){int c;c = getchar();while (c != EOF) {putchar(c);c = getchar();}}The standard library provides several functions for reading or writing one character at a time, of whichgetcharandputcharare the simplest. Each time it is called,getcharreads thenext input characterfrom a text stream and returns that as its value. That is, afterc = getchar();

the variable c contains the next character of input. However, why is the type of c int rather than char?

The problem is distinguishing the end of the input from valid data. The solution is thatgetcharreturns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is called EOF, for "end of file." EOF is an integer defined in<stdio.h>, but the specific numeric value doesn’t matter as long as it is not the same as anycharvalue. By using the symbolic constant, we are assured that noting in the program depends on the specific numeric value. We must declarecto be a type big enough to hold any value thatgetcharreturns. We can’t usecharsincecmust be big enough to holdEOFin addition to any possiblechar. Therefore we usrint.

ReferenceThe C Programming Language

,都成为命途中美丽的点缀,看天,看雪,安安静静,不言不语都是好风景。

Why do we use int rather than char

相关文章:

你感兴趣的文章:

标签云: