Next: Pointers to functions Up: Arguments with main() Previous: Arguments with main()

The command-line argument mechanism

We will demonstrate this with a program which simply echoes whatever you type on the command line. We need one new piece of C syntax: this is a form of if...then...else, but which yields a value rather than executing a block of code. The new syntax is:

   test_expression  ?  expression_1 : expression_2

This has the value of expression_1 if test_expression evaluates to true; otherwise it has the value expression_2.

int main   /* echo arguments: array version */
   (
   int argc,     /* count of how many arguments */
                 /* the Count */
   char *argv[]  /* a pointer to an array of pointers to strings */
                 /* the Values */
   )
{
int i;

for (i= 1; i< argc; i++)
   printf("%s%c", argv[i], (i<argc-1) ? ' ' : '\n');
}

However, we could also note that argv is a pointer to an array of pointers, and write it this way:

int main   /* echo arguments: pointer version */
   (
   int argc,     /* count of how many arguments */
   char *argv[]  /* the arguments, in an array of pointers to strings */
                 /* could be: char **argv */
   )
{
while (--argc > 0)
   printf("%s%c", *++argv, (argc > 1) ? ' ' : '\n');
}

or even as:

   printf( (argc>1) ? "%s " : "%s\n", *++argv);

which shows that the format argument can be an expression.

One other thing to note here: argc counts the program name as well (and so is at least 1) and argv[0] is that name.

Exercises

1. Write a program which prints out its own name, even if the user renames it.

2. Write a program whose behaviour depends on what it is called.

3. Write a program, one_arg, designed to take one integer argument, which prints out that integer if there is exactly one argument, but prints Usage: one_arg <int> otherwise.



Next: Pointers to functions Up: Arguments with main() Previous: Arguments with main()


maspjw@
Tue Sep 27 15:29:34 BST 1994