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

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!

Tags:

C

Char