Friday, July 29, 2016

C Basics - Program Startup and Termination in C

Every C program has a primary (main) function that must be named main. Every C Program should have exactly one main function. main( ) is a collective name given to a set of statements. This name has to be main( ), it cannot be anything else.

The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program. The main function is not predefined by the compiler. It must be supplied in the program text.

The declaration syntax for main is

int main();

Functions within the source program perform one or more specific tasks. The main function can call these functions to perform their respective tasks. When main calls another function, it passes execution control to the function, so that execution begins at the first statement in the function. A function returns control to main when a return statement is executed or when the end of the function is reached.

You can declare any function, including main, to have parameters. The term "parameter" or "formal parameter" refers to the identifier that receives a value passed to a function. When one function calls another, the called function receives values for its parameters from the calling function. These values are called "arguments." You can declare formal parameters to main so that it can receive arguments from the command line using this format:

int main(int argc, char *argv[]);

The arguments in the prototype allow convenient command-line parsing of arguments. The argument definitions are as follows:
argc - An integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1.
argv - An array of null-terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0] is the command with which the program is invoked, argv[1] is the first command-line argument, and so on, until argv[argc], which is always NULL. The first command-line argument is always argv[1] and the last one is argv[argc – 1].

Several restrictions apply to the main function that do not apply to any other C functions. The main function:
Cannot be declared as inline.
Cannot be declared as static.
Cannot have its address taken.
Cannot be called.

You can terminate a C program by using return. Executing a return statement from main causes the program to end its execution.

#include <stdio .h>

int main()

   printf("Hello World!");

   /*User application*/

   return 0; /*exit program*/

You may want to force the termination of a program. To do so, use the exit function.

Related topics:
Intro of C   |   Overview of C   |   Features of C   |   Applications of C   |   The Setup for C   |   Source Program in C   |   Program Structure in C   |   First Program in C   |   Must Know Terms in C

List of topics: C Programming

No comments:

Post a Comment