How exactly is this function an example of a char to int conversion?

• A+
Category：Languages

The book The C Programming Language by Kernighan and Ritchie, second edition states on page 43 in the chapter about Type Conversions:

Another example of `char` to `int` conversion is the function `lower`, which maps a single character to lower case for the ASCII character set. If the character is not an upper case letter, `lower` returns returns it unchanged.

``/* lower: convert c to lower case; ASCII only */ int lower(int c) {     if (c >= 'A' && c <= 'Z')         return c + 'a' - 'A';     else         return c; } ``

It isn't mentioned explicitly in the text so I'd like to make sure I understand it correctly: The conversion happens when you call the `lower` function with a variable of type `char`, doesn't it? Especially, the expression

``c >= 'A' ``

has nothing to do with a conversion from `int` to `char` since a character constant like `'A'` is handled as an `int` internally from the start, isn't it? Edit: Or is this different (e.g. a character constant being treated as a `char`) for ANSI C, which the book covers?

K&R C is old. Really old. Many particulars of K&R C are no longer true in up-to-date standard C.

In stadard, up-to-date C11, there is no conversion to/from `char` in the function you posted:

``/* lower: convert c to lower case; ASCII only */ int lower(int c) {     if (c >= 'A' && c <= 'Z')         return c + 'a' - 'A';     else         return c; } ``

The function accepts `int` arguments as `int c`, and per 6.4.4.4 Character constants of the C standard, character literals are of type `int`.

Thus the entire `lower` function, as posted, under C11 deals entirely with `int` values.

The conversion, if any, is may be done when the function is called:

``char upperA = 'A`;  // this will implicitly promote the upperA char // value to an int value char lowerA = lower( upperA ); ``

Note that this is one of the differences between C and C++. In C++, character literals are of type `char`, not `int`.