All Courses
C Basics

Anatomy of a C Program

To write valid, compileable code in C, you must understand how a C source file is organized and processed by the system.

1. The Global Structure of a Source File

A typical C source file (.c) contains the following sections in order: 1. Header Comments: Author name, file description, and copyright notice. 2. Preprocessor Directives: #include and #define statements. 3. Global Variables & Type Definitions: Declared outside functions (used sparingly). 4. Function Prototypes: Declares function signatures before definition. 5. The main() Function: The required entry point of execution. 6. User Functions: Actual implementations of custom functions.

/*
 * File: calculator.c
 * Author: Prime Coding Hub
 * Description: A basic arithmetic calculator.
 */

#include <stdio.h>    // Standard Input/Output
#define MAX_LIMIT 100 // Preprocessor constant macro

int add(int a, int b); // Function Prototype

int main() {
    int result = add(10, 20);
    printf("Result: %d\n", result);
    return 0;
}

// Function definition
int add(int a, int b) {
    return a + b;
}

2. Preprocessor Directives in Depth

Lines beginning with # are directives for the C preprocessor. The preprocessor scans the file before compiling and modifies the text: - #include <stdio.h>: The angle brackets < > tell the preprocessor to search standard system directories for the file stdio.h. - #include "my_file.h": Double quotes " " tell the preprocessor to search the local directory first, then standard system libraries. - #define MAX_LIMIT 100: This creates a macro. Every occurrence of MAX_LIMIT in the code is replaced with the literal value 100 before compiling.

3. The main() Signature Variations

You will see two common signatures for the main function: - int main(void) or int main(): Represents a main function that takes no arguments from the command line. - int main(int argc, char *argv[]): Represents a main function that accepts parameters from the terminal. argc counts the number of arguments, and argv is an array of strings containing the argument values.

4. Statements, Expressions, and Whitespace

  • Expressions: Code that evaluates to a value (e.g., 10 + 20).
  • Statements: Instructions that perform an action (e.g., x = 10 + 20;). Statements in C must end with a semicolon.
  • Whitespace: C is a free-form language. Spaces, tabs, and newlines are ignored by the compiler except as word boundaries. However, consistent indentation is critical for readability.

5. Commenting Standards

C supports two styles of comments: - Line comments: // ignores everything to the end of the line. - Block comments: /* ... */ can span multiple lines. They cannot be nested.

/* This is a multi-line comment.
   The compiler ignores all of this. */

int x = 5; // This is a single-line comment.

Recommended Conventions

  • Indent code inside curly braces by 4 spaces.
  • Always initialize your variables when declaring them to avoid garbage memory values.