main() function
main() Function
All C language programs must have a main() function. It's the core of every program. It's required. The main() function doesn't really have to do anything other than be present inside your C source code. Eventually, it contains instructions that tell the computer to carry out whatever task your program is designed to do. But it's not officially required to do anything.
A program shall contain a global function named
main
, which is the designated start of the program.
Also called as Driver Function.
int main () { body } | (1) | ||||||||
int main ( int argc, char *argv[]) { body } | (2) | ||||||||
int main ( int argc, char *argv[] , other_parameters ) { body } | (3) | ||||||||
argc | - | Non-negative value representing the number of arguments passed to the program from the environment in which the program is run. |
argv | - | Pointer to the first element of an array of pointers to null-terminated multibyte strings that represent the arguments passed to the program from the execution environment (argv[0]through argv[argc-1]). The value of argv[argc] is guaranteed to be 0. |
body | - | The body of the main function |
other_parameters | - | Implementations may allow additional forms of the main function as long as the return type remains int . A very common extension is passing a third argument of type char*[] pointing at an array of pointers to the execution environment variables. |
The names
argc
and argv
are arbitrary, as well as the representation of the types of the parameters:
int main(int ac, char** av) is equally valid.
The
main
function is called at program startup. It is the designated entry point to a program that is executed in hosted environment (that is, with an operating system). The entry points to freestanding programs (boot loaders, OS kernels, etc) are implementation-defined.
The parameters of the two-parameter form of the main function allow arbitrary multi byte character strings to be passed from the execution environment (these are typically known as command line arguments), the pointers
argv[1] .. argv[argc-1]
point at the first characters in each of these strings. argv[0]
is the pointer to the initial character of a null-terminated multibyte strings that represents the name used to invoke the program itself (or an empty string "" if this is not supported by the execution environment). The strings are modifiable, although these modifications do not propagate back to the execution environment: they can be used, for example, with std::strtok. The size of the array pointed to by argv
is at least argc+1
, and the last element, argv[argc]
, is guaranteed to be a null pointer.Labels: C Programming ( Unit 2 )
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home