x

C – Command line arguments

Prev     Next

C Command line arguments:


main() function of a C program accepts arguments from command line or from other shell scripts by following commands. They are,

  • argc
  • argv[]

where,

argc    – Number of arguments in the command line including program name
argv[]   – This is carrying all the arguments

  • In real time application, it will happen to pass arguments to the main program itself.  These arguments are passed to the main () function while executing binary file from command line.
  • For example, when we compile a program (test.c), we get executable file in the name “test”.
  • Now, we run the executable “test” along with 4 arguments in command line like below.

./test this is a program

Where,


argc             =       5
argv[0]         =       “test”
argv[1]         =       “this”
argv[2]         =       “is”
argv[3]         =       “a”
argv[4]         =       “program”
argv[5]         =       NULL

Example program for argc() and argv() functions in C:

 

Output:

Program name : test
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)

Continue on C – Variable length arguments….

Prev     Next



Like it? Please Spread the word!