Understanding the Structure of C Programs

Aug 23, 2024

Structure of a C Program

Introduction

  • Overview of the lecture on the structure of a C program.
  • Previous topics covered: Introduction to C, basics of programming, low-level vs. high-level languages, language translators, features of the C language.

Basic Structure of a C Program

  • A C program consists of various sections, some essential and some optional.

1. Documentation Section (Comment Section)

  • Purpose: To provide information about the program.
    • Information to include:
      • Author's name
      • Date and time of development
      • Brief description of the program (e.g., "Program for addition of two numbers")
  • Comments are ignored by the compiler (two types):
    • Single-line comment: //
    • Multi-line comment: /* comment */
  • Importance: Enhances readability and understanding of the program.

2. Link Section

  • Purpose: To include header files containing predefined functions.
  • Common header files:
    • #include <stdio.h>
      • Provides functions for input/output (e.g., printf, scanf).
    • #include <conio.h>
      • Provides console input/output functions (e.g., getch).
    • #include <math.h>
      • Provides mathematical functions (e.g., sqrt, pow).
    • #include <string.h>
      • Provides string manipulation functions (e.g., strlen, strcmp).

3. Definition Section

  • Purpose: To define symbolic constants and macros.
  • Example: #define PI 3.14
    • Allows for easy updates and code readability.

4. Global Declaration Section

  • Declare variables and functions that can be accessed throughout the program.
  • Local variables: Accessible only within the function they are defined.
  • Global variables: Accessible from any function in the program.

5. Main Section

  • Compulsory: Every C program must have one main function.
  • Structure of main:
    int main() {
        // declarations
        // executable statements
        return 0;
    }
    
  • Control flow starts at the main function.

6. Sub Program Section

  • Contains user-defined functions.
  • These can be placed after the main function but are not compulsory.

Example Program

  • Basic Program: Print "Hello World"
    #include <stdio.h>
    int main() {
        printf("Hello World");
        return 0;
    }
    
  • Addition Program Example:
    • Documentation section included for clarity.
    • Link section and definition using macros.

Conclusion

  • Summary of the structure of a C program, highlighting the importance of each section.
  • Next topic: Compilation process and converting programs into object code.