IT232 C Programming

C ProgrammingUnit 18 min read

C Basics: Structure, Compilation, and First Program

Unit 1 of C Programming introduces the language’s core concepts—its history, structure, compilation process, and syntax—through a hands-on "Hello, World!" example, while contrasting C with other languages and explaining its widespread use in systems programming.

TAKEAWAYS:

  • C is a procedural, mid-level language designed for efficiency and hardware control, with a strict compilation model (preprocessor → compiler → assembler → linker).
  • A C program’s basic structure includes #include directives, main(), and functions, all written in a case-sensitive syntax.
  • The compilation process transforms source code (.c) into an executable (.exe or binary) via four key stages: preprocessing, compilation, assembly, and linking.
  • Portability in C relies on standard libraries (e.g., stdio.h) and adherence to ANSI/ISO standards, though low-level operations (e.g., memory management) require platform-specific code.
  • Common pitfalls include missing semicolons, incorrect header files, and undefined behavior from uninitialized variables or type mismatches.
  • C’s real-world dominance spans operating systems (Linux), embedded systems (Arduino), and high-performance applications (databases, game engines).

1. Why Learn C?

C is the foundation of modern programming. It was developed in 1972 by Dennis Ritchie at Bell Labs to write the Unix operating system. Its design principles make it:

  • Fast: Compiled directly to machine code with minimal runtime overhead.
  • Portable: Write once, compile anywhere (with minor adjustments).
  • Powerful: Direct hardware access (memory, registers, I/O) and low-level control.

C vs. Other Languages

Feature C Python JavaScript
Type System Static (compile-time) Dynamic (runtime) Dynamic
Memory Mgmt Manual (malloc/free) Automatic (GC) Automatic (GC)
Speed Near machine code Interpreted (slow) JIT-compiled (fast)
Use Case OS, embedded, drivers Scripting, AI Web apps, browsers

2. Structure of a C Program

Every C program follows a modular structure:

  1. Preprocessor Directives (#include, #define): Include libraries and macros.
  2. Function Definitions: Code organized into reusable blocks (e.g., main()).
  3. Statements: End with semicolons (;).
  4. Comments: // (C99+) or /* ... */.

Example: "Hello, World!"

#include <stdio.h>  // Preprocessor directive: include standard I/O library

int main() {        // Main function: entry point
    printf("Hello, World!\n");  // Print statement
    return 0;       // Exit status: success
}

Trace of Execution:

Step Action Output/State
1 #include <stdio.h> Loads printf function
2 main() called Program starts
3 printf("Hello, World!\n") Prints text to console
4 return 0; Exits with status code 0

3. The Compilation Process

C code is not interpreted—it must be compiled into machine code. The process has four stages:

flowchart TD
    A["Source Code (.c)"] --> B["Preprocessor"]
    B --> C["Compiler"]
    C --> D["Assembler"]
    D --> E["Linker"]
    E --> F["Executable (.exe)"]

Stage 1: Preprocessing

  • Replaces macros (#define), includes headers (#include), and removes comments.
  • Example:
    #define PI 3.14159
    #include <stdio.h>
    
    → Expands PI and includes stdio.h.

Stage 2: Compilation

  • Converts preprocessed code into assembly language (human-readable machine code).
  • Example output (x86 assembly snippet):
    section .text
    global main
    main:
        mov eax, 4      ; syscall for write
        mov ebx, 1      ; stdout
        mov ecx, msg    ; message address
        mov edx, 13     ; message length
        int 0x80        ; invoke kernel
        ret
    

Stage 3: Assembly

  • Converts assembly into machine code (binary .o or .obj files).
  • Example (hex dump of printf call):
    55                push ebp
    89 E5             mov ebp, esp
    83 EC 10          sub esp, 16
    C7 04 24 48 00    mov dword [esp], offset msg
    E8 00 00 00 00    call printf
    

Stage 4: Linking

  • Combines object files and libraries into an executable.
  • Resolves external references (e.g., printf from libc).

Real-World Example:

  • Linux Kernel: Written in C, compiled for x86/ARM architectures.
  • Arduino IDE: Uses C/C++ to compile sketches into hex files for microcontrollers.

4. Writing Your First Program: Step-by-Step

Step 1: Write the Code

Save as hello.c:

#include <stdio.h>

int main() {
    printf("Hello, TU Students!\n");
    return 0;
}

Step 2: Compile

On Linux/macOS:

gcc hello.c -o hello

On Windows (MinGW):

gcc hello.c -o hello.exe

Step 3: Run

./hello   # Linux/macOS
hello.exe # Windows

Output:

Hello, TU Students!

5. Common Errors and Debugging

Error Type Cause Fix
Syntax Error Missing ; or { Check brackets/parentheses
Undefined Ref Missing #include Add #include <stdio.h>
Segmentation Fault Dereferencing NULL pointer Initialize pointers properly
Warning: Implicit Decl Undeclared variables Declare variables with int x;

Example Debugging Trace:

#include <stdio.h>
int main() {
    int a = 5;
    printf("%d", b);  // Error: 'b' undeclared
    return 0;
}

Fix:

int b = 10;  // Declare 'b' before use

6. In the Real World

C’s low-level control and speed make it indispensable in:

  1. eSewa (Nepal):

    • Use Case: Backend services for payment processing.
    • Why C? High-performance transaction handling (e.g., malloc for dynamic memory in fraud detection).
    • Example: A queue system to manage payment requests:
      #include <stdio.h>
      #define MAX 100
      int queue[MAX], front = -1, rear = -1;
      
      void enqueue(int x) {
          if (rear == MAX - 1) printf("Queue full!\n");
          else {
              queue[++rear] = x;
              if (front == -1) front = 0;
          }
      }
      
      Visualization:
      flowchart TD
          A["Payment Request"] --> B["Enqueue"]
          B --> C["Process (FIFO)"]
          C --> D["Complete"]
  2. Ncell (Nepal):

    • Use Case: Baseband processors in 4G/5G modems.
    • Why C? Direct hardware access for signal processing (e.g., FFT algorithms in libfft.c).
  3. Google (Worldwide):

    • Use Case: Borg, Google’s internal cluster manager (written in C++ but relies on C for low-level scheduling).
    • Why C? Efficient memory management for container orchestration.

7. Exam Tip

Focus on these high-yield topics:

  1. Compilation Process:
    • Memorize the 4 stages (preprocessor → compiler → assembler → linker).
    • Know the role of #include and #define.
  2. Program Structure:
    • Every program must have a main() function.
    • return 0; indicates successful execution.
  3. Common Errors:
    • Missing semicolons, undeclared variables, and incorrect headers are frequent exam traps.
  4. Real-World Applications:
    • Link C to systems programming (OS, drivers) and embedded systems (Arduino, IoT).
  5. Code Tracing:
    • Practice tracing simple programs (e.g., printf calls, variable assignments) step-by-step.

Past Exam Question Analysis:

  • Question: "What are the different data types in C programming?" Answer: Focus on fundamental types (int, float, char) and derived types (arrays, pointers, structures). Avoid listing all library types (e.g., FILE*).

Visual Summary:

mindmap
  root((C Programming Basics))
    History
      1972: Dennis Ritchie
      Unix OS
    Structure
      #include
      main()
      Functions
    Compilation
      Preprocessor
      Compiler
      Assembler
      Linker
    Real-World
      eSewa: Queues
      Ncell: Signal Processing
      Google: Borg Scheduler

Based on the TU BITM syllabus for C Programming (IT232), unit 1.

Discussion

Loading…