Saturday, October 6, 2012

Is main() function A Mandatory In C Programming ?

Every ' C '  Program Must Contain A Function , At least One :
It doesn't  Mean That It Must be main() Function.

         A  Statement, For Execution Must Be The Part Of A Function Block.

Case :- 1

# include<stdio.h>
printf( " Before Function \n" );
main()

{
printf( " In Function \n" );
}
printf( " After Function \n" );


O/P :- Results In An ERRORS .
(As The Statements printf( " Before Function \n" ); and printf( " After Function \n" ); are not part of Function block They Result In Errors)




Case  :- 2

# include<stdio.h>
hello()

{
printf( " Before Function \n" );
}
main()

{
printf( " In Function \n" );
}

O/P : - In Function

Note :- main() Is The Function Where The Execution Starts And Ends . So , The Above Code Results In Respective O/P , And As There Is No Call To hello() It Has Not Been Executed.
If main() Doesn't Exist The Functions Will Be Called In The Order Of Their Appearance.

C Programming Without main() : -


void first(void)
{
printf("in FIRST\n");
second();
exit(0);
}

second()
{
printf("in SECOND\n");
third();
}

third()
{
printf("in Third\n");
}

Command to compile : cc -nostartfiles filename.c 

O/P :- 
in FIRST
in SECOND
in Third

Note:- Absence of exit(0) in the Above Code Results In An Error Called Segmentation Fault Which Occurs When The Operating System Requests The Central Processing Unit For The Access Of A Physically Non-Existing Address.


So, It is Suggested To Use main() , Because It Knows The Default Entry And Exit Points Itself . Relieving Us From Providing Them Externally , Using Special Code Like exit(0) and Commands Like cc -nostartfiles ...