Reputation: 13779
Why character functions accept int argument instead of char argument?
<ctype.h>
int isalnum(int c);
int isalpha(int c);
int iscntrl(int c);
int isdigit(int c);
int isgraph(int c);
int islower(int c);
int isprint(int c);
int ispunct(int c);
int isspace(int c);
int isupper(int c);
int isxdigit(int c);
int tolower(int c);
int toupper(int c);
Upvotes: 12
Views: 2081
Reputation: 939
Yes, it could be to accommodate EOF which is always a non-char value, though the exact value of EOF could vary with different systems but it'll never be same as any character code.
Upvotes: 0
Reputation: 882716
Characters and integers are rather tightly knit in C.
When you receive a character from an input stream, it must be able to represent every single character plus the end-of-file symbol.
That means a char
type won't be big enough so they use a wider type.
The C99 rationale document states:
Since these functions are often used primarily as macros, their domain is restricted to the small positive integers representable in an unsigned char, plus the value of EOF. EOF is traditionally -1, but may be any negative integer, and hence distinguishable from any valid character code. These macros may thus be efficiently implemented by using the argument as an index into a small array of attributes.
The standard itself has this to say:
The header
<ctype.h>
declares several functions useful for classifying and mapping characters. In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF. If the argument has any other value, the behavior is undefined.
Upvotes: 13
Reputation: 81337
When C was first invented, there was no compile-time checking of function arguments. If one called foo(bar,boz)
, and bar
and boz
were of type int
, the compiler would push two int
values on the stack, call foo
, and hope it was expecting to get two int
values. Since integer types smaller than int
are promoted to int
when evaluating expressions, C functions which were written prior to the invention of prototypes could not pass any smaller integer type.
Upvotes: 5
Reputation: 490728
They have to accept EOF in addition to normal character values. They also predate the invention of function prototypes. At that time, there was no way to pass a char
to a function -- it was always promoted to int
first.
Upvotes: 3