I am writing a program in C that takes several command line arguments. argv[1] will be a single character "option", either an 'a' or 'b' or 'c', each option causing the program to run differently. I would like to begin my program's main() method with an if-statement that checks the whether the option the user specified on the command line is correct, i.e. either an 'a' or 'b' or 'c', and nothing else.
My code:
int main (int argc, char *argv[])
{
if (argv[1] != 'a' || 'b' || 'c') printf("Failure\n");
else printf("Success\n");
}
When I compile this code, I am getting this warning:
warning: comparison between pointer and integer
I understand that I am misusing the pointer to the char array, but I don't understand how I am.
In the expression
if (argv[1] != 'a' || 'b' || 'c')
type of argv[1]
is char*
and type of 'a'
is char
, which is converted to an int
by the compiler. That explains the compiler warning message.
That line is not going to work the way you want it to. You need something like:
if (argv[1][0] != 'a' &&
argv[1][0] != 'b' &&
argv[1][0] != 'c')
{
printf("Failure\n");
}
To make the program more robust, you need to first check whether there are is an argument before you check its contents.
int main (int argc, char *argv[])
{
if ( argc > 1 )
{
if (argv[1][0] != 'a' &&
argv[1][0] != 'b' &&
argv[1][0] != 'c')
{
printf("Failure\n");
}
else
{
printf("Success\n");
}
}
else
{
printf("Failure\n");
}
return 0;
}