The following function uses int
as the second argument type,
memchr(const void *buf, int ch, size_t count);
Though it is used
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.
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.
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!
C never passes arguments smaller than an int to a function. Defining a function argument as char or short is always promoted to an int and defining an unsigned char or unsigned short argument is always promoted to an unsigned int.
If the unsigned vs signed char were the issue, they would have used a short (I don't recall a single platform where a short is 1 byte long).
And of course using an int handles the unsigned vs signed char possibility as memchr is only comparing equality.