tolower() / toupper()
Functions that convert between uppercase and lowercase letters. They are defined in <ctype.h> and are commonly used for case-insensitive string comparison and input normalization.
Syntax
// Converts an uppercase letter to lowercase. Non-alphabetic characters are returned unchanged. // Parameter: a value of type unsigned char (or EOF). // Return value: the converted character as an int. int tolower(int c); // Converts a lowercase letter to uppercase. Non-alphabetic characters are returned unchanged. int toupper(int c);
Conversion targets
| Input | tolower() | toupper() |
|---|---|---|
| Uppercase (A–Z) | Converts to the corresponding lowercase letter. | Returns the character unchanged. |
| Lowercase (a–z) | Returns the character unchanged. | Converts to the corresponding uppercase letter. |
| Digits, symbols, non-ASCII characters | Returns the character unchanged. | Returns the character unchanged. |
Sample code
#include <stdio.h>
#include <ctype.h>
#include <string.h>
// Converts all characters in a string to lowercase in-place.
void str_tolower(char *s) {
for (; *s; s++) {
*s = (char)tolower((unsigned char)*s);
}
}
// Case-insensitive string comparison.
int strcasecmp_manual(const char *a, const char *b) {
while (*a && *b) {
int diff = tolower((unsigned char)*a) - tolower((unsigned char)*b);
if (diff != 0) return diff;
a++; b++;
}
return tolower((unsigned char)*a) - tolower((unsigned char)*b);
}
int main(void) {
// Convert a single character with tolower.
printf("tolower('A') = %c\n", tolower('A')); // Outputs 'a'.
printf("toupper('z') = %c\n", toupper('z')); // Outputs 'Z'.
printf("tolower('3') = %c\n", tolower('3')); // Outputs '3' (no change).
// Convert an entire string to lowercase.
char str[] = "Hello, WORLD! 123";
str_tolower(str);
printf("Lowercase: %s\n", str); // Outputs 'hello, world! 123'.
// Compare strings ignoring case.
int cmp = strcasecmp_manual("Apple", "apple");
printf("Compare \"Apple\" and \"apple\": %d\n", cmp); // Outputs '0' (equal).
return 0;
}
Notes
Passing a char variable directly to tolower() / toupper() can cause undefined behavior if the signed char holds a negative value. Always cast to (unsigned char) before passing the value.
These functions are locale-dependent. In the default ("C") locale, only ASCII letters A–Z and a–z are subject to conversion. To convert accented or other extended characters, you need to set an appropriate locale.
For checking character types, see also isalpha() / isdigit().
If you find any errors or copyright issues, please contact us.