Apart from the errors pointed out by others, you might at some point want to do proper command line parsing. On a POSIX system , this is done with the getopt() library function declared in the unistd.h header (this is not "C standard" C code).
I've extended your requirements with an option -x that takes an integer argument that says what x should be set to:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int x = 0; /* default zero for x */
int i, tmp;
int opt;
char *endptr;
/* the ':' in the string means "the previous letter takes an argument" */
while ((opt = getopt(argc, argv, "lsx:")) != -1) {
switch (opt) {
case 'l':
x = 1;
break;
case 's':
x = 2;
break;
case 'x':
/* validate input, must be integer */
tmp = (int)strtol(optarg, &endptr, 10);
if (*optarg == '\0' || *endptr != '\0')
printf("Illegal value for x: '%s'\n", optarg);
else
x = tmp;
break;
case '?': /* fallthrough */
default:
/* call routine that outputs usage info here */
puts("Expected -s, -l or -x N");
}
}
argc -= optind; /* adjust */
argv += optind; /* adjust */
printf("x = %d\n", x);
puts("Other things on the command line:");
for (i = 0; i < argc; ++i)
printf("\t%s\n", argv[i]);
return EXIT_SUCCESS;
}
Running it:
$ ./a.out -l
x = 1
Other things on the command line:
$ ./a.out -s
x = 2
Other things on the command line:
The last option "wins":
$ ./a.out -s -x -78
x = -78
Other things on the command line:
Here, -s is last:
$ ./a.out -s -x -78 -ls
x = 2
Other things on the command line:
$ ./a.out -s -q
./a.out: illegal option -- q
Expected -s, -l or -x N
x = 2
Other things on the command line:
Parsing stops at the first non-option:
$ ./a.out -s "hello world" 8 9 -x 90
x = 2
Other things on the command line:
hello world
8
9
-x
90
*argv == '-s'?