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.
Why is function 'lower' has int as return type and input type?
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;
}
To map typically 257 different values like the tolower(). With int lower(char c) { and c < 0, this could function differently than tolower().
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 anint, the value of which shall be representable as anunsigned charor shall equal the value of the macroEOF. 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]));
Its most likely attempting to mimic the tolower function which uses int.
A similar question on tolower using an int is here. Why putchar, toupper, tolower, etc. take a int instead of a char?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With