ANSI C: Why do character functions accept an int argument instead of a char argument?

Why do character functions accept an int argument instead of a 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); 
+6
source share
4 answers

Symbols and integers are pretty closely related in C.

When you get a character from an input stream, it should be able to represent each individual character plus the end-of-file character.

This means that the char type will not be large enough to use a wider type.

The justification document C99 says:

Since these functions are often used primarily as macros, their domain is limited to small positive integers represented in an unsigned char, plus an EOF value. EOF is traditionally -1, but can be any negative integer and therefore be different from any valid character code. Thus, these macros can be efficiently implemented using the argument as an index in a small array of attributes.

The standard itself says this:

The <ctype.h> declares several functions useful for classifying and matching characters. In all cases, the argument is an int whose value must be represented as an unsigned char or equal to the value of the EOF macro. If the argument has any other value, the behavior is undefined.

+9
source

They must accept EOF in addition to normal character values. They also precede the invention of function prototypes. At that time, it was not possible to pass the char function to a function - it was always upgraded to int .

+3
source

When C was first invented, no function arguments were checked at compile time. If one of them is called foo(bar,boz) , and bar and boz are of type int , the compiler will push two int values ​​on the stack, call foo and hope that it expects to get two int values. Since when evaluating expressions using integer types less than int to int , the C functions that were written before the invention of the prototypes could not pass a single smaller integer type.

+3
source

Yes, it can be to host an EOF, which is always a non-char value, although the exact value of an EOF may vary from system to system, but it will never be the same as any character code.

0
source

Source: https://habr.com/ru/post/908590/


All Articles