C Program Structure
Understanding the basic structure of C programs is a fundamental foundation for learning the C language. This chapter will detailed introduce the components, execution flow, and basic syntax rules of C programs.
Basic Structure of C Programs
The Simplest C Program
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}Complete C Program Structure
/*
* Program name: complete_example.c
* Author: Programmer
* Description: Complete C program structure example
*/
// 1. Preprocessor directives
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
#define PI 3.14159
// 2. Global variable declarations
int global_counter = 0;
char program_name[] = "Complete Example";
// 3. Function declarations (prototypes)
int add_numbers(int a, int b);
void print_header(void);
void print_footer(void);
// 4. Main function
int main() {
// Local variable declarations
int num1 = 10;
int num2 = 20;
int result;
// Function calls
print_header();
// Calculation and output
result = add_numbers(num1, num2);
printf("Result: %d + %d = %d\n", num1, num2, result);
print_footer();
return 0; // Program ends normally
}
// 5. Function definitions
int add_numbers(int a, int b) {
global_counter++;
return a + b;
}
void print_header(void) {
printf("=== %s ===\n", program_name);
printf("Program started.\n");
}
void print_footer(void) {
printf("Function calls: %d\n", global_counter);
printf("Program ended.\n");
}Detailed Program Structure Explanation
1. Preprocessor Directives
Preprocessor directives start with # and are processed by the preprocessor before compilation.
Header File Inclusion
#include <stdio.h> // Standard library header file, using angle brackets
#include "myheader.h" // User-defined header file, using double quotesMacro Definitions
#define MAX_SIZE 100 // Simple macro
#define SQUARE(x) ((x) * (x)) // Function-like macro
#define DEBUG 1 // Conditional compilation flag
// Using macros
int array[MAX_SIZE];
int area = SQUARE(5); // Expands to ((5) * (5))Conditional Compilation
#ifdef DEBUG
printf("Debug mode enabled\n");
#endif
#ifndef MAX_SIZE
#define MAX_SIZE 50
#endif
#if MAX_SIZE > 100
#error "MAX_SIZE too large"
#endif2. Global Declarations
Global Variables
// Global variable declaration and initialization
int global_var = 42; // Initialized global variable
int uninitialized_global; // Uninitialized (automatically initialized to 0)
static int file_scope_var; // File scope variable
extern int external_var; // External variable declarationConstant Definitions
const int MAX_USERS = 1000; // Read-only variable
const char* PROGRAM_VERSION = "1.0.0";3. Function Declarations
Function prototypes tell the compiler the name, return type, and parameter types of a function.
// Function declaration syntax
return_type function_name(type1 param1, type2 param2, ...);
// Examples
int calculate_sum(int a, int b); // With parameters and return value
void print_message(char* message); // With parameters and no return value
int get_random_number(void); // No parameters and with return value
void initialize_system(void); // No parameters and no return value4. Main Function
The main function is the entry point of the program, with two standard forms:
Standard Form 1: No Command-Line Arguments
int main(void) {
// Program code
return 0;
}Standard Form 2: With Command-Line Arguments
int main(int argc, char* argv[]) {
// argc: Number of arguments
// argv: Array of arguments
printf("Program name: %s\n", argv[0]);
printf("Number of arguments: %d\n", argc);
for (int i = 1; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
return 0;
}Meaning of Return Values
int main() {
// Program logic
return 0; // Success
return 1; // General error
return -1; // Severe error
// Other non-zero values represent different types of errors
}5. Function Definitions
A function definition consists of a function header and a function body:
return_type function_name(parameter_list) {
// Local variable declarations
// Function body
return return_value; // If return type is not void
}
// Examples
int multiply(int x, int y) {
int result = x * y;
return result;
}
void print_array(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}Program Execution Flow
Compilation Process
Source code(.c) → Preprocessor → Compiler → Assembler → Linker → Executable fileDetailed Steps
- Preprocessing - Processes
#include,#define, and other directives - Compilation - Converts C code to assembly code
- Assembly - Converts assembly code to machine code
- Linking - Links multiple object files and libraries into an executable
# View output of each stage
gcc -E program.c -o program.i # Preprocessing
gcc -S program.c -o program.s # Compile to assembly
gcc -c program.c -o program.o # Compile to object file
gcc program.o -o program # LinkingRuntime Execution Flow
#include <stdio.h>
// Global variables are initialized at program startup
int global_count = 0;
void function_a() {
printf("Function A called\n");
global_count++;
}
void function_b() {
printf("Function B called\n");
global_count++;
}
int main() {
printf("Program started\n"); // 1. Program starts here
function_a(); // 2. Call function A
function_b(); // 3. Call function B
printf("Total calls: %d\n", global_count); // 4. Output results
return 0; // 5. Program ends
}Best Practices for Code Organization
1. File Organization
Header File (header.h)
// math_utils.h
#ifndef MATH_UTILS_H
#define MATH_UTILS_H
// Constant definitions
#define PI 3.14159265359
// Function declarations
double calculate_area(double radius);
double calculate_circumference(double radius);
int factorial(int n);
// Structure declaration
typedef struct {
double x;
double y;
} Point;
#endif // MATH_UTILS_HImplementation File (source.c)
// math_utils.c
#include "math_utils.h"
#include <stdio.h>
double calculate_area(double radius) {
return PI * radius * radius;
}
double calculate_circumference(double radius) {
return 2 * PI * radius;
}
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}Main Program File
// main.c
#include <stdio.h>
#include "math_utils.h"
int main() {
double radius = 5.0;
printf("Circle with radius %.2f:\n", radius);
printf("Area: %.2f\n", calculate_area(radius));
printf("Circumference: %.2f\n", calculate_circumference(radius));
int n = 5;
printf("Factorial of %d: %d\n", n, factorial(n));
return 0;
}2. Coding Style
Naming Conventions
// Variables and functions: lowercase letters and underscores
int user_count;
char* file_name;
void calculate_average(void);
// Constants: uppercase letters and underscores
#define MAX_BUFFER_SIZE 1024
#define DEFAULT_TIMEOUT 30
// Type definitions: capitalized or all uppercase
typedef struct Point Point;
typedef enum { RED, GREEN, BLUE } Color;Code Formatting
// Recommended code formatting
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int i;
int numbers[MAX_SIZE];
// Initialize array
for (i = 0; i < MAX_SIZE; i++) {
numbers[i] = i * 2;
}
// Output first 10 numbers
for (i = 0; i < 10; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}3. Commenting Conventions
File Header Comment
/*
* File name: calculator.c
* Author: John Doe
* Creation date: 2024-01-15
* Description: Simple calculator program supporting basic arithmetic operations
* Version: 1.0
*/Function Comment
/**
* Calculate the greatest common divisor of two integers
*
* @param a First integer
* @param b Second integer
* @return Greatest common divisor
*/
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}Inline Comments
int main() {
int x = 10; // Initialize variable
int y = 20; // Second operand
// Calculate and output result
int sum = x + y;
printf("Sum: %d\n", sum);
return 0; // Program ends normally
}Common Program Patterns
1. Simple Input/Output Program
#include <stdio.h>
int main() {
char name[50];
int age;
// Get user input
printf("Please enter your name: ");
scanf("%49s", name); // Limit input length to prevent overflow
printf("Please enter your age: ");
scanf("%d", &age);
// Output results
printf("Hello, %s! You are %d years old.\n", name, age);
return 0;
}2. Menu-Driven Program
#include <stdio.h>
void show_menu() {
printf("\n=== Calculator Menu ===\n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("0. Exit\n");
printf("Please select an operation: ");
}
int main() {
int choice;
double a, b, result;
do {
show_menu();
scanf("%d", &choice);
if (choice >= 1 && choice <= 4) {
printf("Please enter two numbers: ");
scanf("%lf %lf", &a, &b);
}
switch (choice) {
case 1:
result = a + b;
printf("Result: %.2f + %.2f = %.2f\n", a, b, result);
break;
case 2:
result = a - b;
printf("Result: %.2f - %.2f = %.2f\n", a, b, result);
break;
case 3:
result = a * b;
printf("Result: %.2f * %.2f = %.2f\n", a, b, result);
break;
case 4:
if (b != 0) {
result = a / b;
printf("Result: %.2f / %.2f = %.2f\n", a, b, result);
} else {
printf("Error: Division by zero!\n");
}
break;
case 0:
printf("Program exiting.\n");
break;
default:
printf("Invalid choice, please try again.\n");
}
} while (choice != 0);
return 0;
}3. Data Processing Program
#include <stdio.h>
#include <stdlib.h>
#define MAX_STUDENTS 100
typedef struct {
char name[50];
int id;
float score;
} Student;
void input_students(Student students[], int count) {
for (int i = 0; i < count; i++) {
printf("Enter information for student %d:\n", i + 1);
printf("Name: ");
scanf("%49s", students[i].name);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Score: ");
scanf("%f", &students[i].score);
}
}
void print_students(Student students[], int count) {
printf("\nStudent Information List:\n");
printf("%-20s %-10s %-10s\n", "Name", "ID", "Score");
printf("----------------------------------------\n");
for (int i = 0; i < count; i++) {
printf("%-20s %-10d %-10.2f\n",
students[i].name,
students[i].id,
students[i].score);
}
}
float calculate_average(Student students[], int count) {
float sum = 0;
for (int i = 0; i < count; i++) {
sum += students[i].score;
}
return sum / count;
}
int main() {
Student students[MAX_STUDENTS];
int count;
printf("Please enter the number of students: ");
scanf("%d", &count);
if (count > MAX_STUDENTS) {
printf("Number of students exceeds limit!\n");
return 1;
}
input_students(students, count);
print_students(students, count);
float average = calculate_average(students, count);
printf("\nAverage score: %.2f\n", average);
return 0;
}Debugging and Testing
1. Adding Debug Information
#include <stdio.h>
#define DEBUG 1
#if DEBUG
#define DBG_PRINT(fmt, ...) \
printf("[DEBUG] %s:%d: " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define DBG_PRINT(fmt, ...)
#endif
int factorial(int n) {
DBG_PRINT("Calculating factorial of %d\n", n);
if (n <= 1) {
DBG_PRINT("Base case: returning 1\n");
return 1;
}
int result = n * factorial(n - 1);
DBG_PRINT("%d! = %d\n", n, result);
return result;
}
int main() {
int n = 5;
int result = factorial(n);
printf("Result: %d! = %d\n", n, result);
return 0;
}2. Error Handling
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int safe_divide(int a, int b, int* result) {
if (b == 0) {
fprintf(stderr, "Error: Division by zero\n");
return -1; // Error code
}
*result = a / b;
return 0; // Success
}
int main() {
int a = 10, b = 0, result;
if (safe_divide(a, b, &result) == 0) {
printf("Result: %d / %d = %d\n", a, b, result);
} else {
printf("Calculation failed\n");
return 1;
}
return 0;
}Summary
This chapter detailed introduced the structure of C programs, including:
- Basic Components - Preprocessor directives, declarations, main function, function definitions
- Execution Flow - Compilation process and runtime flow
- Code Organization - File separation, naming conventions, commenting guidelines
- Common Patterns - Input/output, menu-driven, data processing programs
- Debugging Techniques - Debug information and error handling
Understanding program structure is fundamental to writing high-quality C code. Good program structure can:
- Improve code readability
- Facilitate maintenance and debugging
- Support modular development
- Reduce error occurrence
In the next chapter, we will learn C Basic Syntax, and dive deeper into the syntax rules and programming conventions of the C language.
Remember:
- Keep code structure clear
- Use meaningful names
- Add appropriate comments
- Follow coding conventions
- Handle error conditions promptly