Can anyone tell me why I'm getting "number 1" as my output when i enter arguments 1, 2, 3. It seems like its always 1 and I don't know why.

int main(int argc, char *argv[]) {

         if (argv[1] = "1"){
            printf("number 1");
         }else if(argv[1] = "2"){
            printf("number 2");
         }else if(argv[1] = "3"){
            printf("number 3");
         }else{
            printf("Missing a case number");
         }
}

Can anyone tell me why I'm getting "number 1" as my output when i enter arguments 1, 2, 3. It seems like its always 1 and I don't know why.

int main(int argc, char *argv[]) {

         if (argv[1] = "1"){
            printf("number 1");
         }else if(argv[1] = "2"){
            printf("number 2");
         }else if(argv[1] = "3"){
            printf("number 3");
         }else{
            printf("Missing a case number");
         }
}

It is because you are assigning the value to argv[1] every time in your if condition. Use == instead of =

It is because you are assigning the value to argv[1] every time in your if condition. Use == instead of =

Wrong. As Dave said, comparison of char arrays (aka "C style strings") should usually use strcmp() rather than ==.

Don't forget to check argc value before argv[1] using, for example:

if (argc > 1) {
    switch (*argv[1]) {
    case '1':
          ...
          break;
    case '2':
        ...
    default:
        ...
    }
} else {
    /* argv[1] is NULL! */
}
This article has been dead for over six months. Start a new discussion instead.