A C program is a set of declarations and function definitions; execution starts at main, and its return value becomes the process exit status.
Anatomy of a program
/* 1. Preprocessor directives */
#include <stdio.h>
#define GREETING "Hi"
/* 2. Global declarations */
static int counter = 0;
/* 3. Function prototype (declaration) */
int square(int x);
/* 4. main: the entry point */
int main(void) {
counter++;
printf("%s! square(7) = %d, counter = %d\n", GREETING, square(7), counter);
return 0; /* 0 = success */
}
/* 5. Function definitions */
int square(int x) {
return x * x;
}Hi! square(7) = 49, counter = 1Valid signatures of main
| Signature | Use |
|---|---|
int main(void) | No command-line arguments. |
int main(int argc, char *argv[]) | With arguments (char **argv is identical). |
void main() | Not standard C. Some compilers accept it; never write it. |
return 0;orreturn EXIT_SUCCESS;means success;EXIT_FAILURE(from<stdlib.h>) means failure.Reaching the closing
}ofmainwithoutreturnis treated asreturn 0;(C99+) — but only formain.int main()with empty parentheses means unspecified arguments in C17; prefer(void).
Comments
#include <stdio.h>
int main(void) {
/* block comment — can span
several lines, but cannot be nested */
int x = 5; // line comment (C99+)
printf("%d\n", x);
return 0;
}5Declarations vs definitions
What happens before main runs?
What does the return value of main mean?