Writing C main function
This question already has an answer here:
The return value of main()
is used to indicate success or failure to its parent process. More generally, it can be used to communicate back specific statuses as well, though C doesn't define those.
If main()
returns 0
or EXIT_SUCCESS
, then the program was successful. EXIT_FAILURE
or non-zero, then it failed.
The void
in the parameter list simply says that it takes no arguments. This is because of a (mis)feature of C which allows you to declare a function without fully specifying the paramters it takes. A function declared int func();
can be called with any number of parameters, but int func(void);
can only becalled with zero.
Example
on linux,
two trivial programs:
$ cat ret0.c
int main (void) { return 0; }
$ cat ret42.c
int main (void) { return 42; }
Then in `bash` we can look at
$ ./ret0 ; echo $?
0
$ ./ret42 ; echo $?
42
So it's possible to use that status when calling your program.
The int
return is there to give an error indicator back to the OS. return 0
means no error, all other codes (typically return 1
) indicates the program could not finish successfully. Other programs (eg, shell scripts) can use this error code to determine if your program executed its task, or ran into a problem.
void
just means no arguments. It's the same as
int main()
{
/* program */
}
but more explicit.
A program can take command line arguments, in which case main
must be defined as
int main(int argc /* number of arguments */, char *argv[] /* arguments)
{
/* program
}
Any good book on C should explain this.
First off let us forget about main. In C(not C++) if you define a function with no parameters like this
int f(){ return 0;}
It is legal to call such a function with any number of arguments:
int a = f(); /* legal */
int a = f("help", 1, 2.0); /* legal */
If you want your function f
to only work with exactly no arguments you can amend it like this:
int f(void){return 0;}
int a = f(); /* legal */
int a = f("help", 1, 2.0); /* not legal as it has too many parameters */
The same thing applies to main()
and main(void)
. In most cases in the reasonable world most people would never care however I have encountered legal code that calls main
within the program.
So declaring main
like:
int main() {
/* Do a bunch of stuff here */
}
Allows for code elsewhere in your program to do this:
main();
main(1,2,3,4);
By declaring main(void)
you add a compiler check that prevents the latter example main(1,2,3,4)
from compiling.
上一篇: 同时声明错误的傻瓜证明
下一篇: 写C主要功能