とらりもんHOME  Index  Search  Changes  Login

C intro 7. argument

To give some information to a program, you can do it from the command line as well as standard input. As an example, consider the following program:

   /* add2.c
    * usage (example): $ ./add2 1.2 3.6
    * compile: $ gcc add2.c -o add2
    * 2018/07/16 K. Nasahara
    */
   # include <stdio.h>
   # include <stdlib.h>
   main(int argc, char **argv)
   {float x, y;
    x=atof(argv[1]);
    y=atof(argv[2]);
    printf("%f + %f = %f\n", x, y, x+y);
   }

Now let's compile and run:

$ gcc add2.c -o add2
$ ./add2 1.2 3.6
1.200000 + 3.600000 = 4.800000 

This is a program to answer the sum of two numbers. We have made similar program before, but this is a little different. This program takes two numbers in the command line at the same time of starting the program, whereas the program we made last time took numbers from standard input (after starting the program). This style is suitable for controlling parameters in the program and used frequently. The data given to the program in this style (on the command line) are called arguments.

Let's see the detail. First, we replaced usual "main()" by "main(int argc, char **argv)". "argc" and "argv" are conventional words which are used in such case. "argc" automatically takes a value of numbers the arguments. "argv" is "a pointer to a pointer". We skip the details about it here. In short, argv[0] describes the command name, argv[1] describes the first argument, argv[2] describes the second argument, and so on.

Note that the arguments are described in strings (array of characters). Therefore, "1.2" is not recognized as a number but a word or a sentence. The line

x=atof(argv[1]);

converts this "word" to a real number. This "atof" function needs to be defined at the beginning of the program, which is done by "#include stdlib.h" at the head of the program. For your interest, you use "atoi" instead of "atof" if you want to convert a word to an integer.


Exercise 7-1: Get a number in the command line and calculate sum of the integers from 1 to that number.

[Go back to C language introduction]

Last modified:2018/10/22 11:48:28
Keyword(s):
References:[C language introduction]