While in the progress of making string functions, I have tried building a function somewhere similar to strlwr()
which I named lowercase()
:
#include <stdio.h>
#include <ctype.h>
char *lowercase(char *text);
int main() {
char *hello = "Hello, world!";
printf("%s\n", lowercase(hello));
}
char *lowercase(char *text) {
for (int i = 0; ; i++) {
if (isalpha(text[i])) {
(int) text[i] += ('a' - 'A');
continue;
} else if (text[i] == '\0') {
break;
}
}
return text;
}
I learned that the gap for a big letter and small letter would be 32, which is what I used. But then I got this error:
lowercase.c:14:13: error: assignment to cast is illegal, lvalue casts are not supported
(int) text[i] += 32;
^~~~~~~~~~~~~ ~~
I want to increment the value of the char if it is considered a letter from A-Z. Turns out I can't, since the char is in an array, and the way I'm doing it doesn't seem to make sense for the computer.
Q: What alternate ways can I use to complete this function? Can you explain further why this error is like this?
Though in C string literals have types of non-constant character arrays nevertheless you may not change string literals.
From the C Standard (6.4.5 String literals)
So you should declare the identifier
hello
like a character arrayWithin the function you should not use magic numbers like
32
. For example if the compiler uses the EBCDIC coding your function will produce a wrong result.And in the loop instead of the type
int
you have to use the typesize_t
because an object of the type int can be unable to store all values of the typesize_t
that is the return type of thesizeof
operator or of the functionstrlen
.This statement
does not make a sense because in the left side of the expression there is an rvalue due to the casting.
The function can be implemented the following way