开发者

Why 'fputc' use an INT as its parameter instead of CHAR?

standard C lib:

int fputc(int c , FILE *stream);

And开发者_运维问答 such behaviors occured many times, e.g:

    int putc(int c, FILE *stream);
    int putchar(int c);

why not use CHAR as it really is? If use INT is necessary, when should I use INT instead of CHAR?


Most likely (in my opinion, since much of the rationale behind early C is lost in the depths of time), it it was simply to mirror the types used in the fgetc type functions which must be able to return any real character plus the EOF special character. The fgetc function gets the next character converted to an int, and uses a special marker value EOF to indicate the end of the stream.

To do that, they needed the wider int type since a char isn't quite large enough to hold all possible characters plus one more thing.

And, since the developers of C seemed to prefer a rather minimalist approach to code, it makes sense that they would use the same type, to allow for code such as:

filecopy(ifp, ofp)
    FILE *ifp;
    FILE *ofp;
{
    int c;
    while ((c = fgetc (ifp)) != EOF)
        fputc (c, ofp);
}


No char parameters in K&R C

One reason is that in early versions1 of C there were no char parameters.

Yes, you could declare a parameter as char or float but it was considered int or double. Therefore, it would have, then, been somewhat misleading to document an interface as taking a char argument.

I believe this is still true today for functions declared without prototypes, in order for it to be possible to interoperate with older code.


1. Early, but still widespread. C was a quick success and became the first (and still, mostly, the only) widely successful systems programming language.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜