Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 135 ยท Functions

The main Function in Depth

Learn every valid form of main in C, what its return value means, how falling off the end works, and the real difference between return, exit and atexit.

Every C program starts running at main. You have written int main(void) since your first lesson, but main is more special than an ordinary function. The runtime calls it, not your code; its signature is limited to a few forms; its return value becomes the program's exit status; and when it ends, the runtime performs an orderly shutdown. Understanding those details explains why scripts can tell whether your program worked, why return and exit behave a little differently, and why some old-looking forms of main still compile.

The valid signatures

The C standard defines two portable forms. Pick whichever you need:

C
int main(void)                      /* no input from the command line */
int main(int argc, char *argv[])    /* with command-line arguments */

argc is the number of arguments, including the program name itself, and argv is an array of argc strings followed by a NULL pointer. You may name the parameters anything, and char **argv means the same as char *argv[]. The return type must be int. Command-Line Arguments shows how to parse the values.

Some other forms you may meet:

  • int main() is accepted by compilers. Before C23, empty parentheses meant "unspecified parameters", which is not the same as void. In C23 they mean (void). Writing (void) is clearer everywhere.
  • int main(int argc, char *argv[], char *envp[]) gives a third array with environment strings such as HOME=/home/ann. It is a common extension on Unix and Windows but not standard C. Use getenv instead, or the POSIX global environ.
  • void main(void) is wrong for hosted programs. It happens to work on some compilers and breaks the exit status on others. Always use int.
C argc, argv and the NULL terminator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The runner starts the program with no extra arguments, so you only see the first three lines and the final message. The NULL at argv[argc] is guaranteed, which means while (*argv) is a valid way to loop over all arguments.

The return value is the exit status

When main returns, the runtime passes that value to the operating system as the exit status. By convention 0 means success and anything else means some kind of failure. Shells expose it as $?, build tools stop on a nonzero status, and CI systems mark the job red. Use the named constants EXIT_SUCCESS and EXIT_FAILURE from <stdlib.h> when you want portable code; they are 0 and 1 on virtually every system.

On Linux and macOS only the low 8 bits of the status survive, so a status of 256 reads as 0 and 257 as 1. Keep your own codes between 0 and 125: shells reserve 126 and above for things like "command not found" and "killed by a signal".

C Exit statuses are small numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The runner reports the nonzero exit code next to the output. A script could now branch on 3 to tell this particular failure apart from a generic one.

Falling off the end of main

Since C99, reaching the closing brace of main is the same as return 0;. This special rule applies only to main. Any other function that reaches its closing brace without returning a value, and whose caller uses the result, is undefined behavior. Many style guides still write return 0; explicitly, which is harmless and makes the intent obvious.

return versus exit

Inside main, return value; and exit(value); end the program the same way: functions registered with atexit run in reverse order, open streams are flushed and closed, and the status goes to the system. The difference is where you can use them. return leaves only the current function, so it ends the program only when executed in main. exit ends the whole program from anywhere, including deep inside helper functions.

One subtle point: the automatic (local) variables of main are destroyed when main returns, before the atexit handlers run. With exit called from main itself, they are still alive. A handler that uses a pointer to a local variable of main is therefore safe only if the program ends through exit. Make handlers use static or global data to avoid the question.

C exit from a helper, handlers in reverse order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

You'll see the buffered text starting up appear anyway, because exit flushes streams, followed by the two handlers in reverse order. Useful stdlib.h Functions compares exit, abort, _Exit and quick_exit, which skip some or all of that cleanup.

Can main call itself?

In C, yes. In C++ it is forbidden, which surprises people who know both languages. Recursing into main is legal but almost never a good idea; use a normal helper function so the program's structure stays obvious. You also cannot declare main as static or inline in a hosted environment, and the name main is reserved for the program's entry point at file scope.

Do not rely on the value of uninitialized variables or on code running before main. Static initialization (globals with constant initializers) happens before main, but anything that needs a function call at startup belongs inside main.

Structuring a real main

A good main is short. It checks the command-line arguments, calls the functions that do the work, and turns their result into an exit status. Here the work happens in run, which reports failures through its return value, so every path ends at one decision point:

C A small, honest main

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Without an argument the program prints the usage message to stderr and reports failure, which is exactly what a command-line tool should do. Splitting run out of main also makes the logic easy to test and reuse.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these is a standard, portable signature of main?

    The standard defines int main(void) and int main(int argc, char *argv[]). The envp form is a common extension, and void main is not allowed for hosted programs.
  2. 2. A program's main reaches the closing brace without a return statement. What is the exit status?

    Since C99, falling off the end of main is equivalent to return 0. This rule is special to main.
  3. 3. What does argv[argc] contain?

    The standard guarantees a NULL pointer after the last argument, so you can loop until you reach NULL.
  4. 4. How does calling exit(1) inside a helper function differ from return 1 in the same helper?

    return ends only the current function. exit terminates the program from anywhere, runs atexit handlers in reverse order, and flushes and closes streams.
  5. 5. Which exit statuses are safest for your own error codes on Linux and macOS?

    Only the low 8 bits reach the shell, and 126 and above have special meaning there, so use 1 to 125 for custom codes.

Summary

  • Use int main(void) or int main(int argc, char *argv[]); the envp form is a non-standard extension and void main is wrong.
  • argv[0] is the program name (or empty) and argv[argc] is always NULL.
  • The value returned from main becomes the exit status: 0 for success, nonzero for failure; EXIT_SUCCESS and EXIT_FAILURE name them.
  • Falling off the end of main means return 0, and that rule applies to main only.
  • exit ends the program from any function, runs atexit handlers in reverse order and flushes streams; return only leaves the current function.
  • Keep main short: validate input, call the real work, convert the result into a status.

Next: Recursion, where a function calls itself to solve a problem.