First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Structure of a C program

Structure of a C program: its parts (comments, headers, macros, global declarations, main, local declarations, statements, functions), the compilation model, and how to write, compile, and run small programs correctly.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers write C programs that must compile, run, and be easy to maintain. Knowing the structure of a C program helps you organize code, avoid compiler errors, and communicate your intent clearly to teammates and examiners.

Key ideas

  • Source file (.c) — A text file containing C code. The compiler reads it to create an object file.
  • Header file (.h) — A file containing declarations (e.g., function prototypes, macros, type definitions) that can be shared across many source files via the preprocessor directive #include.
  • Comment — Non-executable text in code meant for humans. In C: /* ... */ for block comments and // ... for single-line comments (supported in C99 and later). Comments are removed by the compiler’s preprocessing stage.
  • Preprocessor directive — A command beginning with # that runs before compilation. Common directives: #include (to include headers) and #define (to create macros). The preprocessor performs textual substitution.
  • Macro — A name replaced by its definition during preprocessing. Example: #define PI 3.141592653589793. Macros do not consume memory at runtime; they are text substitutions.
  • Declaration — A statement that introduces a name (identifier) and its type to the compiler. Examples: variable declarations (int a;), function prototypes (int add(int, int);). Declarations do not necessarily allocate storage.
  • Definition — A declaration that also allocates storage or provides the function body. Example: int a; at file scope is a definition; int add(int x, int y) { return x + y; } is a function definition.
  • Scope — The region of a program where an identifier is visible. File scope (global), block scope (inside { }), and function prototype scope are common in C.
  • main function — The designated entry point of a hosted C program: int main(void) or int main(int argc, char *argv[]). Execution starts from main.
  • Statement — A complete instruction in C, ending with ; (except blocks and control structures). Examples: expression statements (a = 3;), selection (if), iteration (for, while).
  • Block — A group of statements enclosed by braces { }. A block can contain its own declarations; these names have block scope.
  • Return value of main — An integer returned by main to the operating system. By convention, 0 means success; a non-zero value indicates an error.
  • Compilation model — The pipeline: preprocessing → compilation → assembly → linking → executable. The linker resolves references to external libraries and multiple object files.

Exact structure, in order most exam answers accept:

  1. Documentation section (comments) — Purpose, author, date, brief description at the top of the file.
  2. Link section (preprocessor includes) — Header inclusions using #include <...> or #include "...".
  3. Definition section (macros and type definitions) — #define for symbolic constants and function-like macros; typedef for type aliases.
  4. Global declaration section — Declarations/definitions of global variables and function prototypes (declarations visible to the whole file or other files when extern).
  5. main function section — Starting point of execution. Contains local declarations, input/output, decision-making, loops, and calls to functions. Ends with return.
  6. Sub-program section (user-defined function definitions) — Bodies of functions defined by the programmer, usually after main (or before, with prototypes as needed).

Note on C standards (exam context):

  • C89/C90: Single-line comments // are not original; many compilers support them. C99 and later standardize //.
  • main’s valid forms in hosted environments are int main(void) and int main(int argc, char *argv[]) (or equivalent char **argv). Returning int is required by the standard; omitting return may compile but is not correct style.

Assumptions often used in university answers:

  • Single-source-file programs for illustration.
  • Standard library functions (e.g., printf, scanf) are available through #include <stdio.h>.
  • int is at least 16 bits; in modern systems it is typically 32 bits. We will not rely on exact widths here.

Diagram to draw (if asked: “Draw and label the structure of a C program”):

  • Draw a vertical stack of labeled boxes in this order from top to bottom:
    1. “Documentation (comments)”
    2. “Preprocessor directives: #include, #define”
    3. “Type definitions (typedef)”
    4. “Global declarations and function prototypes”
    5. “main() { local declarations; statements; }”
    6. “User-defined function definitions”
  • Use arrows downward showing program flow during reading/compilation (not runtime order); add a note that runtime starts inside main(). Label scope: file-scope at 2–4, block-scope inside main and other functions.

Formulas

Syntax to remember (write exactly in your exam answers):

  • Program skeleton: /* brief comment */ #include <stdio.h> #define NAME value typedef existing_type alias; /* global declarations and prototypes */ int main(void) { /* local declarations; statements; return 0; */ } /* function definitions */
  • Header include: #include <header.h> (for standard headers) — #include "myheader.h" (for user headers)
  • Macro definition: #define IDENTIFIER replacement — no semicolon at end
  • Function prototype: return_type function_name(parameter_list);
  • main with no command-line arguments: int main(void)
  • main with command-line arguments: int main(int argc, char *argv[])
  • Variable declaration: type identifier_list; e.g., int a, b;
  • Block: { /* declarations; statements; */ }
  • Return statement: return expression;
  • Comment styles: /* block comment */ and // single-line comment (C99+)

Worked examples

Example 1: Minimal structured program (Hello, World!) Complete code:

/* Program: Hello World — demonstrates minimal structure */
#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0; // success
}

Sample input: (none) Exact output:

Hello, World!

Example 2: Program with macros, prototypes, main, and a user-defined function Problem: Read two integers and print their sum using a separate add function. Show use of #define and a function prototype. Complete code:

/* Program: Sum using a user-defined function */
#include <stdio.h>

#define PROMPT "Enter two integers: "

/* Function prototype (declaration) */
int add(int x, int y);

int main(void) {
    int a, b, s; // local declarations

    printf(PROMPT);
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Invalid input\n");
        return 1; // non-zero means error
    }

    s = add(a, b); // function call
    printf("Sum = %d\n", s);

    return 0;
}

/* Function definition (after main) */
int add(int x, int y) {
    return x + y;
}

Sample input:

10 25

Exact output:

Enter two integers: Sum = 35

(Note: The prompt and result appear on the same line because no newline is printed before the result except the one inside \n at the end of the output line.)

Example 3: Block structure and scope inside main with a helper function Problem: Read an integer radius and print the circumference of a circle using a macro for π and a helper function. Demonstrate local block and clear return from main. Complete code:

/* Program: Circumference of a circle — shows block scope and structure */
#include <stdio.h>

#define PI 3.141592653589793

double circumference(double r); // prototype

int main(void) {
    double r; // local to main

    printf("Enter radius in meters: ");
    if (scanf("%lf", &r) != 1) {
        printf("Invalid input\n");
        return 1;
    }

    {
        // inner block (example of block scope)
        double c = circumference(r);
        printf("Circumference = %.6f m\n", c);
    }

    return 0;
}

double circumference(double r) {
    return 2.0 * PI * r;
}

Sample input:

2.5

Exact output:

Enter radius in meters: Circumference = 15.707963 m

(Checked: 2 × π × 2.5 = 15.707963 when π = 3.141592653589793, printed to 6 decimals.)

Common mistakes

  • Omitting the function prototype when the function is defined after main, leading to implicit-int errors in older C or mismatched parameter types.
  • Using void main() instead of int main(void). The correct return type is int.
  • Not returning a value from main, or returning a non-integer expression.
  • Placing executable statements before local declarations in C89-mode compilers (C99 allows mixed declarations and statements; many compilers default to C11/C17, but exam settings may expect declarations first inside a block).
  • Misusing macros with parentheses, e.g., #define SQR(x) x*x causing precedence bugs; better #define SQR(x) ((x)*(x)). (Structure-wise: remember macros are text substitutions.)
  • Writing #define PI 3.14; with a semicolon; macros should not end with ;.
  • Using uninitialized local variables.
  • Confusing #include "file.h" and #include <file.h>; use angle brackets for standard headers.

For your exam

Expect these question types:

  • Definitions: “Define macro/declaration/definition/scope/prototype/main function.” Give precise one-line definitions with bold key term, and one example.
  • Short notes: “Explain the structure of a C program.” Draw the labeled diagram of sections in order. Mention each part with one line of purpose.
  • Theory with diagram: “Explain the compilation process of a C program.” Describe preprocessing, compilation, assembly, linking, and the role of headers/libraries. Draw a left-to-right pipeline: source → preprocessor → compiler → assembler → linker → executable.
  • Syntax recall: Write the skeleton of a C program with #include, a macro, a prototype, int main(void), and one function definition.
  • Programs: Write a small program that uses a function prototype and function definition separate from main, reads input via scanf, prints via printf, and returns 0 from main. Ensure correct headers, braces, and semicolons. What earns full marks:
  • Correct order and naming of sections; accurate syntax exactly as per C.
  • Clear, labeled diagram if asked; neat, consistent indentation.
  • For programs: compiles as-is, includes necessary headers, prototypes before use, correct int main(void) signature, proper return values, and sample I/O shown.
  • Brief explanation of why each part exists (e.g., macro for constants, header for function declarations).

Quick check

  1. List the usual sections of a C program in order.
  2. Why is a function prototype placed before main when the function is defined after main?
  3. Write the correct signatures for main in a hosted C environment.

Answers: 1) Documentation (comments); Preprocessor directives (#include, #define); Type definitions; Global declarations and function prototypes; int main(...) with local declarations and statements; User-defined function definitions. 2) So the compiler knows the function’s name, return type, and parameter types before it is called, preventing type mismatches and errors. 3) int main(void) and int main(int argc, char *argv[]) (or char **argv).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?