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:
| Type | Syntax | Usage |
|---|---|---|
| Single-line | // comment | Brief 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:
| Directive | Purpose | Example |
|---|---|---|
#include | Include header files | #include <stdio.h> |
#define | Define macros/constants | #define PI 3.14 |
#ifdef | Conditional compilation | #ifdef DEBUG |
#ifndef | If not defined | #ifndef HEADER_H |
#endif | End conditional | #endif |
#undef | Undefine a macro | #undef PI |
#pragma | Compiler 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:
| Header | Purpose |
|---|---|
stdio.h | Input/Output functions (printf, scanf) |
stdlib.h | General utilities (malloc, free, exit) |
string.h | String manipulation functions |
math.h | Mathematical functions |
ctype.h | Character classification |
time.h | Date and time functions |
limits.h | Implementation-defined limits |
float.h | Floating-point limits |
stdbool.h | Boolean type (C99) |
stdint.h | Integer 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 Value | Meaning |
|---|---|
0 | Successful execution |
| Non-zero | Error occurred |
EXIT_SUCCESS | Success (defined in stdlib.h) |
EXIT_FAILURE | Failure (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
#includedirectives - ā¢
#definefor 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
- ā¢Every C program has a standard structure with defined sections
- ā¢Preprocessor directives are processed before compilation
- ā¢main() is the entry point - program execution starts here
- ā¢Function prototypes should be declared before use
- ā¢Comments are essential for documentation and readability
- ā¢Global variables should be used sparingly
- ā¢Return 0 from main() indicates successful execution
āļø Next Topic
Continue to Compilation Process to learn how C source code becomes an executable program.