views:

72

answers:

2

Why doesn't this work? When I try to use -l or -s as the first argument, the if statements don't take. They always go to the else statement.

#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    if (argv[1] == "-l")
    {
        printf("Yay!\n");
    }
    else if (argv[1] == "-s")
    {
        printf("Nay!\n");
    }
    else
    {
        printf("%s\n", argv[1]);
    }
        return 0;
}
+10  A: 

You cannot compare strings using == operator - use strcmp() instead.

By comparing strings using == you are comparing the addresses of char * pointers, not string values.

qrdl
Thanks for the help :)
hahuang65
+4  A: 

In C strings are compares by strcmp function. Instead your compares just pointers. So:

if (strcmp(argv[1],"-l") == 0)
{
    printf("Yay!\n");
}
Dewfy