Why does the function `memchr()` use `int` for the argument of `char` type?

眉间皱痕 提交于 2020-03-13 07:44:45

问题


The following function uses int as the second argument type,

memchr(const void *buf, int ch, size_t count);

Though it is used for a character type. Why is the function defined to use int for the argument of char type? Are there any special reasons for this?


回答1:


It is so because this is a very "old" standard function, which existed from the very early times of C language evolution.

Old versions of C did not have such things as function prototypes. Functions were either left undeclared, or declared with "unknown" parameter list, e.g.

void *memchr(); /* non-prototype declaration */

When calling such functions, all argument were subjected to automatic argument promotions, which means that such functions never received argument values of type char or short. Such arguments were always implicitly promoted by the caller to type int and the function itself actually received an int. (This is still true in modern C for functions declared as shown above, i.e. without prototype.)

When eventually C language developed to the point where prototype function declarations were introduced, it was important to align the new declarations with legacy behavior of standard functions and with already compiled legacy libraries.

This is the reason why you will never see such types as char or short in argument lists of legacy function declarations. For the very same reason you won't see type float used there either.


This also means that if for some reason you have to provide a prototype declaration for some existing legacy function defined in K&R style, you have to remember to specify the promoted parameter types in the prototype. E.g. for the function defined as

int some_KandR_function(a, b, c)
char a;
short b;
float c;
{
}

the proper prototype prototype declaration is actually

int some_KandR_function(int a, int b, double c);

but not

int some_KandR_function(char a, short b, float c); // <- Incorrect!



回答2:


Because char, signed char, and unsigned char are three distinct types. On a specific implementation you don't know whether char is signed or unsigned.

Except in rare systems (see Keith's note), the type int comprises all the values those three types can have.




回答3:


All of the standard functions that deal in characters do. I think the reason is partly historical (in some pre-standard versions of C, a function couldn't take a char or unsigned char argument, just like varargs arguments can't have character type) and partly for consistency across all such functions.

There are a few character-handling functions that have to use int in order to allow for the possibility of EOF, but memchr isn't one of them.



来源:https://stackoverflow.com/questions/15798661/why-does-the-function-memchr-use-int-for-the-argument-of-char-type

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