-5

I am new in c programming. I would like to ask if this function is ok, because I don't know how to check this in main.

char uppertolowertoupper(char ch)
{

    if (ch>='A' && ch<='Z')
    {
        ch=tolower(ch);

        return ch;
    }
    else if (ch>='a' && ch<='a')
    {
        ch=toupper(ch);
        return ch;
    }
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
uppermost
  • 1
  • 5

3 Answers3

2

It may appear to work for you, but it could certainly be improved.

  • Firstly, it's incomplete. You're missing a bracket (and a return statement) at the end.
  • Next, not all C implementations use ASCII. If you were to use this code on systems where EBCDIC is the character set, you'd find that ch>='a' && ch<='z' includes more than just alphabet characters, and similar for ch>='A' && ch<='Z'... I suggest using isupper and islower instead.
  • Finally, tolower and toupper expect arguments that are of type int. Your char arguments will be converted to int but there's more to it than that... The arguments are supposed to be either unsigned char values or EOF. Anything else is undefined behaviour, meaning any signed character values you pass to these functions might cause segfaults (e.g. this question). I recommend changing this function so that it accepts an unsigned char argument (instead of a char argument) and returns an unsigned char.
Community
  • 1
  • 1
autistic
  • 1
  • 3
  • 35
  • 80
1

An error (probably a typo):

    else if (ch>='a' && ch<='a')

This should have been:

    else if (ch>='a' && ch<='z')

Secondly, to call the function in main, something like this should suffice:

char ch;
ch=uppertolowertoupper('c');
printf("%c",ch);

The above works only if you have declared or defined the function before main.

Declared before main:

char uppertolowertoupper(char);
int main()
{

    char ch;
    ch=uppertolowertoupper('c');
    printf("%c",ch);

}
char uppertolowertoupper(char ch)
{
  // your function
}

Defined before main:

char uppertolowertoupper(char ch)
{

if (ch>='A' && ch<='Z')
{
ch=tolower(ch);

return ch;
}
else if (ch>='a' && ch<='z')
{
ch=toupper(ch);
return ch;
}
}
int main(){

 char ch;
 ch=uppertolowertoupper('c');
 printf("%c",ch);
 return 0;
}
Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
0
#include <stdio.h>
#include <ctype.h>

char uppertolowertoupper(char ch){
    if (ch>='A' && ch<='Z'){//if(isupper(ch)){
        ch=tolower(ch);
        return ch;
    } else if (ch>='a' && ch<='z'){//if(islower(ch)){
        ch=toupper(ch);
        return ch;
    }
}

int main(void){
    char test[] = "abcdefghijklmnopqrstrvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.?!";
    puts(test);
    for(char *p = test; *p ; ++p)
        putchar(uppertolowertoupper(*p));
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70