Why are islower() and friends required to handle EOF?

半腔热情 提交于 2019-12-13 14:12:31

问题


Why are islower() and friends required to handle EOF, whereas putchar() and friends don't have to?

Why isn't islower() treating int as unsigned char, as it is the case in putchar()? This would make total sense, because we have to check for EOF first anyway. See also Why the argument type of putchar(), fputc(), and putc() is not char?


回答1:


because we have to check for EOF first anyway.

We absolutely don't.

int c;
while(isspace(c=fgetc(fp)));
if (c==EOF) ...

This is totally legitimate code to skip whitespaces. Checking each character for EOF separately is a waste of time.

The ctype functions are made to handle EOF specifically to enable code like this.

See also this question.




回答2:


None of character type functions are required to handle EOF, other than ignoring it (i.e. returning false). In fact, EOF marker is not even mentioned in <ctype.h> header documentation.

The most likely reason for character classification function signatures to use int in place of char, signed or unsigned, is to avoid implementation-defined behavior in loops like this:

int c;
while ((c =getchar()) != EOF) {
    if (islower(c)) {
        ...
    } else if (isdigi(c)) {
        ...
    }
}

This would compile and run with islower(char) instead of islower(int), but the result would be implementation defined, which is not desirable under such basic circumstances. Essentially, int in the signature of getchar became "contagious," getting into signatures of functions only marginally related to it.



来源:https://stackoverflow.com/questions/40716908/why-are-islower-and-friends-required-to-handle-eof

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!