What is the efficient way to define the main() function in C?

C - main function and program execution.

In every C program, there is a primary function called main. The main function is used as a starting point for the execution of a program. Normally, it controls the execution of a program by directing calls to other functions.

The main function is subject to a number of restrictions that do not apply to any other C functions.

The main function:

  • Can't be declared as inline.
  • Can't be declared as static.
  • Can't have its address taken.
  • Can't be called from your program.

The main function signature:

There is no declaration for the main function since it is a built-in function. The declaration syntax for main would look like this:

int main()
int main(int argc, char* argv[])
which is equivalent to
int main(int argc, char** argv)

One or more specific tasks are performed by functions within the source program. In order to perform their respective tasks, the main function can call these functions. Execution control is passed to the function when main calls another function, so that execution begins at the first statement of the function. Control is returned to main when a return statement is executed or when the function ends.

Parameters can be declared for any function, including main. "Parameter" or "formal parameter" refers to the identifier for the value passed to a function. In C, the parameters used to pass information to the main function are argc and argv, although these names are not required. The types for argc, argv are defined by the C language. You can also declare argv as char** argv.

Termination of main:

The execution of a program usually terminates when it returns from or reaches the end of main, although it may terminate for various reasons at other points in the program. When an error condition is detected, you may wish to force the termination of your program. In order to accomplish this, you can use the exit function.

Return value for main:

The return value for main indicates how the program exited. A normal exit is represented by a return value of 0 from the main function. A non-zero return indicates an abnormal exit, however there is no standard for interpreting non-zero returns.

Follow us on Facebook and Twitter for latest update.