srikar sana srikar sana - 2 months ago 6
C Question

single name for many functions in c - main()

I have come a cross different ways of writing a functions e.g. consider main function in following ways

int main()
{
some thing here;
return 0;
}


Second and third variant could be like

void main()
{
some thing here;
}

int main(int argv , char *argc[])
{
some thing here;
return 0;
}


So how can someone possibly write a single function in different ways? Which could cause errors in my opinion ?

How to write such functions ? Is is similar to overloading overloading or overwriting concept in java ?
Is there a facility to use a single name for many functions ?
Please provide an example of using such functions ?

Answer

I am trying to answer your questions here:

First, main is of course a function. In fact, main is the entry point for every c program, and every c program must have a main function.

A C-Program consists of variables and functions, and MUST have at least one function. In the minimal case, this will be the main function.

Ok, so much for the theory and the first part of your question.

What i think is the thing thats bugging your mind is: You think that main() is a C library function and therefore it cannot be "overloaded".

The truth is, its not a library function, its just a specific entry point for your program, and it identifies itself by the name "main", not the return type or arguments it takes.

You can write a C program with just

main(){
 [your code here]
}

or also

int main(int argc, char * argv[]){
 [your code here]
}

So you declare and define the main function yourself and you do it the way it best fits your program's need (i.e. if your program takes command line variables, you will pick the second example).

Remember, main is not a library function, its just a naming convention where a C-program starts.

You can also have a look at The C Programming Language (Second Edition) by Brian Kernighan and Dennis Ritchie, pages 5-7.