The main() function
When a program begins running, the system calls the function
main
,
which marks the entry point of the program. By default, main
has
the storage class extern
. Every program must have
one function named main
, and the following constraints
apply: - No other function in the program can be called
main
. main
cannot be defined asinline
orstatic
.main
cannot be called from within a program.- The address of
main
cannot be taken. - The
main
function cannot be overloaded. - The
main
function cannot be declared with theconstexpr
specifier.
The function
main
can be defined with
or without parameters, using any of the following forms: int main (void){}
int main ( ){}
int main(int argc, char *argv[]){}
int main (int argc, char ** argv){}
Although any name can be given to these parameters, they
are usually referred to as argc
and argv
.
The first parameter, argc
(argument count) is an
integer that indicates how many arguments were entered on the command
line when the program was started. The
second parameter, argv
(argument vector), is an array
of pointers to arrays of character objects. The array objects are
null-terminated strings, representing the arguments that were entered
on the command line when the program was started. The first
element of the array, argv[0]
, is a pointer to the
character array that contains the program name or invocation name
of the program that is being run from the command line. argv[1]
indicates
the first argument passed to the program, argv[2]
the
second argument, and so on.
The following example program
backward
prints
the arguments entered on a command line such that the last argument
is printed first: #include <stdio.h>
int main(int argc, char *argv[])
{
while (--argc > 0)
printf("%s ", argv[argc]);
printf("\n");
}
Invoking this program from a command line:
backward string1 string2
gives the following output:
string2 string1
The arguments argc
and argv
would
contain the following values at the start of the program:
Object | Value |
---|---|
argc |
3 |
argv[0] |
pointer to string "backward" |
argv[1] |
pointer to string "string1" |
argv[2] |
pointer to string "string2" |
argv[3] |
NULL |
Note: See z/OS XL C/C++ Programming Guide for details about receiving the parameter list (
argv
) in C
main
, preparing your main function to receive parameters, and on
C and C++ parameter passing considerations.