Why is function 'lower' has int as return type and input type?

Viewed 364
int main(void)
{
    char s[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int i;

    i = 0;
    while (s[i] != '\0') {
        printf("%c -> %c\n", s[i], lower(s[i]));
        i++;
    }

    return 0;
}

int lower(int c)
{
    return (c >= 'A' && c<= 'Z') ? c + 'a' - 'A' : c;
}

This is the program to convert all the alphabets to lower case . So in the solution they used a lower function but I don't know why they used int as return type.

2 Answers

Why is function 'lower' has int as return type and input type?

  1. The code is entirely int math. Even if the signature was char c, the code would have an int result due to the usual integer promotions.

    int lower(int c) {
      return (c >= 'A' && c<= 'Z') ? c + 'a' - 'A' : c;
    }
    
  2. To map typically 257 different values like the tolower(). With int lower(char c) { and c < 0, this could function differently than tolower().

  3. int is usually near the native processor integer size and code is usually tightest and fastest with int versus char. This is a C historically choice and compromise. Including original C did not prototype the function signature and all int and sub-int arguments were promoted to int.

7.4 Character handling

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. C11dr §7.4 1

These is...() and to...() functions work in the unsigned char range (and EOF) and not char.

Robust code would avoid negative char when calling tolower() or tolower()-like functions.

// printf("%c -> %c\n", s[i], lower(s[i]));
printf("%c -> %c\n", s[i], lower((unsigned char) s[i]));
Related