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
#includedirectives,main(), and functions, all written in a case-sensitive syntax. - The compilation process transforms source code (
.c) into an executable (.exeor 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:
- Preprocessor Directives (
#include,#define): Include libraries and macros. - Function Definitions: Code organized into reusable blocks (e.g.,
main()). - Statements: End with semicolons (
;). - 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:
→ Expands#define PI 3.14159 #include <stdio.h>PIand includesstdio.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
.oor.objfiles). - Example (hex dump of
printfcall):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.,
printffromlibc).
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:
eSewa (Nepal):
- Use Case: Backend services for payment processing.
- Why C? High-performance transaction handling (e.g.,
mallocfor dynamic memory in fraud detection). - Example: A queue system to manage payment requests:
Visualization:#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; } }flowchart TD A["Payment Request"] --> B["Enqueue"] B --> C["Process (FIFO)"] C --> D["Complete"]
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).
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:
- Compilation Process:
- Memorize the 4 stages (preprocessor → compiler → assembler → linker).
- Know the role of
#includeand#define.
- Program Structure:
- Every program must have a
main()function. return 0;indicates successful execution.
- Every program must have a
- Common Errors:
- Missing semicolons, undeclared variables, and incorrect headers are frequent exam traps.
- Real-World Applications:
- Link C to systems programming (OS, drivers) and embedded systems (Arduino, IoT).
- Code Tracing:
- Practice tracing simple programs (e.g.,
printfcalls, variable assignments) step-by-step.
- Practice tracing simple programs (e.g.,
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 SchedulerBased on the TU BITM syllabus for C Programming (IT232), unit 1.
Discussion
Loading…