Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 867
efie Avatar asked Dec 25 '18 23:12

efie


1 Answers

Character constants have type int, as you expected, so you are correct that there are no promotions to int in this function.

Any promotion that may occur would happen if a variable of type char is passed to this function, and this is most likely what the text is referring to.

The type of character constants is int in both the current C17 standard (section 6.4.4.4p10):

An integer character constant has type int

And in the C89 / ANSI C standard (section 3.1.3.4 under Semantics):

An integer character constant has type int

The latter of which is what K&R Second Edition refers to.

like image 149
dbush Avatar answered Oct 20 '22 22:10

dbush