Docs

README

Structure of a C Program

šŸ“– Introduction

Every C program follows a specific structure. Understanding this structure is fundamental to writing correct and organized C code. This section will break down each component of a C program in detail.


šŸ—ļø Basic Structure Overview

/* Documentation Section */
// Comments describing the program

/* Preprocessor Directives Section */
#include <stdio.h>
#define PI 3.14159

/* Global Declarations Section */
int globalVar;
void myFunction();

/* Main Function Section */
int main() {
    // Local declarations
    int localVar;

    // Statements
    printf("Hello, World!\n");

    return 0;
}

/* User-Defined Functions Section */
void myFunction() {
    // Function body
}

šŸ“ Detailed Breakdown of Each Section

1. Documentation Section

The documentation section contains comments that describe the program, its purpose, author, date, and other relevant information.

/*
 * Program Name: Calculator
 * Author: John Doe
 * Date: 2024-01-15
 * Description: A simple calculator that performs basic arithmetic operations
 * Version: 1.0
 */

Types of Comments:

TypeSyntaxUsage
Single-line// commentBrief explanations
Multi-line/* comment */Detailed descriptions

Best Practices:

  • •Always document your programs
  • •Explain complex logic
  • •Include author and date information
  • •Update comments when code changes

2. Preprocessor Directives Section

Preprocessor directives are instructions to the C preprocessor. They are processed before compilation.

#include <stdio.h>      // Include standard I/O library
#include <stdlib.h>     // Include standard library
#include <string.h>     // Include string library
#include "myheader.h"   // Include custom header file

#define MAX_SIZE 100    // Define a constant
#define PI 3.14159      // Define mathematical constant
#define SQUARE(x) ((x) * (x))  // Define a macro

Common Preprocessor Directives:

DirectivePurposeExample
#includeInclude header files#include <stdio.h>
#defineDefine macros/constants#define PI 3.14
#ifdefConditional compilation#ifdef DEBUG
#ifndefIf not defined#ifndef HEADER_H
#endifEnd conditional#endif
#undefUndefine a macro#undef PI
#pragmaCompiler instructions#pragma once

Header Files Syntax:

#include <filename.h>   // System header (searches system directories)
#include "filename.h"   // User header (searches current directory first)

Standard Library Headers:

HeaderPurpose
stdio.hInput/Output functions (printf, scanf)
stdlib.hGeneral utilities (malloc, free, exit)
string.hString manipulation functions
math.hMathematical functions
ctype.hCharacter classification
time.hDate and time functions
limits.hImplementation-defined limits
float.hFloating-point limits
stdbool.hBoolean type (C99)
stdint.hInteger types (C99)

3. Global Declarations Section

Global declarations are made outside all functions and are accessible throughout the program.

// Global variables
int counter = 0;                    // Global integer variable
char programName[] = "Calculator";  // Global string
float taxRate = 0.08;              // Global float

// Function prototypes (declarations)
int add(int a, int b);
void displayMenu();
float calculateTax(float amount);

// Type definitions
typedef unsigned long ulong;
typedef struct {
    int x;
    int y;
} Point;

// Enumerations
enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

// Structure definitions
struct Student {
    int id;
    char name[50];
    float gpa;
};

Why Use Global Declarations?

  • •Share data between functions
  • •Define constants used program-wide
  • •Declare function prototypes for organization
  • •Define custom types used throughout the program

āš ļø Warning About Global Variables:

  • •Use sparingly - they can make debugging difficult
  • •Any function can modify them
  • •Can lead to unexpected side effects
  • •Prefer passing parameters to functions

4. The Main Function

The main() function is the entry point of every C program. Execution always begins here.

int main() {
    // Program code here
    return 0;
}

Different Forms of main():

// Form 1: Standard (most common)
int main() {
    return 0;
}

// Form 2: With void parameter (explicit no arguments)
int main(void) {
    return 0;
}

// Form 3: With command-line arguments
int main(int argc, char *argv[]) {
    // argc = argument count
    // argv = argument vector (array of strings)
    return 0;
}

// Form 4: Alternative command-line arguments
int main(int argc, char **argv) {
    return 0;
}

Understanding main()'s Return Value:

Return ValueMeaning
0Successful execution
Non-zeroError occurred
EXIT_SUCCESSSuccess (defined in stdlib.h)
EXIT_FAILUREFailure (defined in stdlib.h)
#include <stdlib.h>

int main() {
    if (errorCondition) {
        return EXIT_FAILURE;  // Return 1
    }
    return EXIT_SUCCESS;      // Return 0
}

Structure Inside main():

int main() {
    // 1. Local variable declarations
    int count;
    float sum = 0.0;
    char name[50];

    // 2. Executable statements
    printf("Enter count: ");
    scanf("%d", &count);

    // 3. Function calls
    processData(count);

    // 4. Control structures
    if (count > 0) {
        // do something
    }

    for (int i = 0; i < count; i++) {
        sum += i;
    }

    // 5. Return statement
    return 0;
}

5. User-Defined Functions Section

User-defined functions contain code for specific tasks. They are defined after main() or before with prototypes.

// Function prototype (declaration)
int add(int a, int b);

int main() {
    int result = add(5, 3);
    printf("Sum: %d\n", result);
    return 0;
}

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

Function Components:

return_type function_name(parameter_list) {
    // Function body
    // Local declarations
    // Statements
    return value;  // Optional for void functions
}

Examples:

// Function with no parameters and no return value
void greet() {
    printf("Hello!\n");
}

// Function with parameters and return value
int multiply(int x, int y) {
    return x * y;
}

// Function with pointer parameters (pass by reference)
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Function returning a pointer
int* findMax(int *arr, int size) {
    int *max = &arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > *max) {
            max = &arr[i];
        }
    }
    return max;
}

šŸ” Complete Program Example

Here's a complete program demonstrating all sections:

/*
 * ============================================================
 * Program: Simple Grade Calculator
 * Author: Student
 * Date: 2024
 * Description: Calculates and displays student grade based on marks
 * ============================================================
 */

/* Preprocessor Directives */
#include <stdio.h>
#include <stdlib.h>

#define PASSING_MARKS 40
#define MAX_MARKS 100

/* Global Declarations */
int totalStudents = 0;

// Function prototypes
char calculateGrade(int marks);
void displayResult(char name[], int marks, char grade);

/* Main Function */
int main() {
    // Local declarations
    char studentName[50];
    int studentMarks;
    char grade;

    // Get input
    printf("Enter student name: ");
    scanf("%s", studentName);

    printf("Enter marks (0-%d): ", MAX_MARKS);
    scanf("%d", &studentMarks);

    // Validate input
    if (studentMarks < 0 || studentMarks > MAX_MARKS) {
        printf("Invalid marks!\n");
        return EXIT_FAILURE;
    }

    // Process
    grade = calculateGrade(studentMarks);
    totalStudents++;

    // Output
    displayResult(studentName, studentMarks, grade);

    return EXIT_SUCCESS;
}

/* User-Defined Functions */

// Calculate grade based on marks
char calculateGrade(int marks) {
    if (marks >= 90) return 'A';
    else if (marks >= 80) return 'B';
    else if (marks >= 70) return 'C';
    else if (marks >= 60) return 'D';
    else if (marks >= PASSING_MARKS) return 'E';
    else return 'F';
}

// Display the result
void displayResult(char name[], int marks, char grade) {
    printf("\n--- Result ---\n");
    printf("Name: %s\n", name);
    printf("Marks: %d/%d\n", marks, MAX_MARKS);
    printf("Grade: %c\n", grade);

    if (grade != 'F') {
        printf("Status: PASSED\n");
    } else {
        printf("Status: FAILED\n");
    }

    printf("Total students processed: %d\n", totalStudents);
}

šŸ“‹ Program Structure Checklist

When writing a C program, ensure you have:

  • • Documentation/comments at the top
  • • All necessary #include directives
  • • #define for constants and macros
  • • Global variables (if needed) declared
  • • Function prototypes declared
  • • main() function with proper return type
  • • Local variables declared at the start of blocks
  • • Proper indentation and formatting
  • • All functions defined after main() or before with prototypes
  • • Return statement in main()

šŸŽÆ Memory Layout

Understanding how a C program is stored in memory:

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”  High Address
│       Command Line          │
│       Arguments             │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│         Stack               │  ← Local variables, function calls
│           ↓                 │     Grows downward
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│                             │
│    (Unused Space)           │
│                             │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│           ↑                 │
│         Heap                │  ← Dynamic allocation (malloc)
│                             │     Grows upward
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│    Uninitialized Data       │  ← Global/static variables
│         (BSS)               │     (initialized to 0)
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│    Initialized Data         │  ← Global/static variables
│        (Data)               │     (with initial values)
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│         Text                │  ← Program code
│      (Code Segment)         │     (read-only)
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜  Low Address

šŸ”‘ Key Takeaways

  1. •Every C program has a standard structure with defined sections
  2. •Preprocessor directives are processed before compilation
  3. •main() is the entry point - program execution starts here
  4. •Function prototypes should be declared before use
  5. •Comments are essential for documentation and readability
  6. •Global variables should be used sparingly
  7. •Return 0 from main() indicates successful execution

ā­ļø Next Topic

Continue to Compilation Process to learn how C source code becomes an executable program.

README - C Programming Tutorial | DeepML