Why do we use int rather than char

我的主力博客:半亩方塘

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 which  getchar  and  putchar  are the simplest. Each time it is called,  getchar  reads the  next input character  from a text stream and returns that as its value. That is, after

c = 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 that getcharreturns 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 anychar value. By using the symbolic constant, we are assured that noting in the program depends on the specific numeric value. We must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we usr int.

Reference

The C Programming Language
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值