C Workshop · The main Function
Lesson C

The main Function

The operating system calls main. When main returns, the program is done.

What it is

main is the front door. The operating system starts your program by calling main, and when main returns, the program is over. Everything else you write is either called from here or never runs.

Approach

  1. Declare int main(void).
  2. Put startup work in the body — here, one printf.
  3. Return 0 so scripts and shells treat the run as successful.

Where this is used in the real world

Diagram

1

OS

loads the executable

Your code is not running yet.
2

main

your statements run

This is the only entry in this program.
3

return 0

status code

Non-zero usually means failure.
4

OS

reaps the process

The program is done.

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2int main(void) {
3  printf("main ran\n");
4  return 0;
5}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. Who calls main?

The OS starts the process at main.

2. int main(void) means:

void = no args; int = status.

3. A non-zero return from main usually means:

Convention: 0 ok, non-zero error.

4. When main returns, the program is:

Returning ends the hosted program.

5. Command-line arguments use which form later?

argc/argv is the hosted args form.