Search code examples
cor-operator

Comparison between argv[1] and string in C programming


I wrote some code where I try to compare the argv[1] with the string "o" and the string "m" and print an error if I don't find it in argv[]. The problem is, that the program doesn't work as expected. This is what I have done:

int main(int argc, char *argv[])
{
  if((strcmp(argv[1], "o") != 0) || (strcmp(argv[1], "m") != 0))
  {
    printf("error\n");
  }
    return 0;
}

Solution

  • Your check

    if((strcmp(argv[1], "o") != 0) || (strcmp(argv[1], "m") != 0))
    {
        printf("error\n");
    }
    

    Can be translated in

    Raise an error if the first argument of the program IS NOT equal to 'o' AND at the same time IS NOT equal to 'm'

    (in fact, strcmp () returns 0 when the compared strings are equal)

    The only possible way to avoid the error would be that the argument is equal to 'o' and to 'm' at the same time. Which is obviously impossible.

    You have two options. First you can perform a positive check:

    if((strcmp(argv[1], "o") == 0) || (strcmp(argv[1], "m") == 0))
    {
        ...
    }
    else
    {
        printf("error\n");
    }
    

    Or a negative check (like yours). In this case you need that the argument is not 'o' AND it is NOT 'm' (logic operator &&):

    if((strcmp(argv[1], "o") != 0) && (strcmp(argv[1], "m") != 0))
    {
        printf("error\n");
    }