-1

Here I have a code which checks the string, if first element is lower case, it should change it to uppercase. when I run it, it works for those strings which their first element is lowercase but it also works for other strings and it shouldn't. when I debugged it in Code::Blocks, I realized that when code wants to execute the function, it jumps into if body and it doesn't check the condition. I would appreciate any help.

#include <stdio.h>
#include <stdlib.h>

int main() {
   char name[30];
   fgets(name, sizeof(name), stdin);
   printf("name: ");
   puts(name);
   upper(name);
   puts(name);
   return 0;
}
void upper (char *a)
{


    if (97 <= *a <= 122)
    {
        *a -= 32;
    }
}
  • Don't use numeric values for character codes unless you cannot avoid it at all. When I read your code, do you think I should have to remember what various character codes are? 'a' works just fie and is readable. – gnasher729 Aug 09 '20 at 08:11

1 Answers1

1

97 <= *a <= 122 is treated as (97 <= *a) <= 122.

97 <= *a will be evaluated to 0 or 1, so (97 <= *a) <= 122 will always become true.

You should use 97 <= *a && *a <= 122 instead.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70