The main() Function
Every C program needs exactly one main function. It's the entry point — the single place the operating system knows to jump to when your program starts running. Without it, there's nothing for the linker to point to, and the build fails.
The two standard signatures
main can be written in two standard forms, depending on whether your program needs command-line arguments:
int main(void) {
/* no command-line arguments needed */
return 0;
}int main(int argc, char *argv[]) {
/* argc = argument count, argv = argument values */
return 0;
}argc and argv let your program read whatever was typed after its name on the command line — the full details of working with them are covered in the command-line arguments page. For programs that don't need input from the command line, int main(void) is the simpler and more common choice.
Comparing the two forms
Signature | When to use it |
|---|---|
int main(void) | The program never reads command-line arguments — the vast majority of introductory programs. |
int main(int argc, char *argv[]) | The program needs to read arguments passed when it was launched, e.g. |
What the return value means
The int that main returns is the program's exit status. By convention, 0 means the program completed successfully, and any non-zero value signals that something went wrong (different non-zero values can be used to distinguish different kinds of failure).
Omitting return
Since C99, if execution reaches the closing } of main without hitting a return statement, the compiler automatically returns 0 for you — as if the program succeeded. This is a special rule that applies only to main; every other function that isn't declared void requires an explicit return.