I. What Is Procedural Programming?
Procedural Programming (POP) is a programming paradigm that takes procedures or functions as its basic unit of organization.
It emphasizes that a program should be organized according to the steps of solving a problem: a complex task is split into multiple relatively independent operational procedures, and the overall functionality is achieved through sequential execution, conditional judgment, loops, and function calls.
The core questions that procedural programming focuses on are:
- What operations does the program need to perform?
- In what order is each operation executed?
- How is data passed between different operations?
- How can repeated logic be extracted into functions?
- How can control structures manage the program's execution path?
For example, a bank transfer program can be split into:
- Validate the source account.
- Validate the destination account.
- Check the account balance.
- Deduct the balance from the source account.
- Add the balance to the destination account.
- Record the transaction result.
Procedural design mainly organizes the program around these operational steps.
1. Core Idea
The core of procedural programming is:
View a program as a combination of a series of operational procedures, in which data is passed between procedures and the program executes according to the control flow.
A typical procedural program can be abstracted as:
flowchart TD
A["Receive input data"] --> B["Perform data processing"]
B --> C["Call business functions"]
C --> D["Perform calculation and judgment"]
D --> E["Return processing result"]
E --> F["Output result"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Procedural programming does not mean that only linear code can be written. Conditional branches, loops, recursion, and function calls are all important parts of it.
II. Basic Components of Procedural Programming
Procedural programming is generally composed of data, functions, control structures, and calling relationships.
1. Data
Data is the object that a program processes.
For example:
int price = 100;
int quantity = 5;
int total = price * quantity;
Here:
price: unit price of the item.quantity: quantity of the item.total: the calculation result.
In procedural programming, data is usually represented by data structures such as variables, arrays, and structs.
Functions receive data through parameters and output processing results through return values or other mechanisms.
2. Functions
Functions are one of the most important organizational units in procedural programming.
They encapsulate a piece of code with a specific responsibility, providing reusable operations through the function name, parameters, and return value.
int calculate(int price, int quantity) {
return price * quantity;
}
int main() {
int total = calculate(100, 5);
return 0;
}
Functions serve the following purposes:
- Encapsulate repeated logic.
- Break down complex tasks.
- Increase code reuse.
- Reduce the cost of understanding local code.
- Establish clear calling relationships.
A function does not necessarily have to return a numeric value; declaring it as void or similar can indicate that there is no return value.
3. Control Structures
Control structures determine the program's execution path.
Common control structures include:
| Control structure | Purpose | Common syntax |
|---|---|---|
| Sequential structure | Execute in code order | Ordinary statements |
| Branch structure | Choose an execution path based on a condition | if, switch |
| Loop structure | Repeatedly execute a block of code | for, while |
| Jump structure | Change the normal execution position | break, continue, return |
Sequential structure
int a = 10;
int b = 20;
int result = a + b;
The program executes in the order of the statements.
Branch structure
if (score >= 60) {
printf("及格");
} else {
printf("不及格");
}
The program selects different execution paths based on the condition.
Loop Structure
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
The program repeatedly executes the loop body until the loop condition is no longer satisfied.
4. Data Passing
Functions typically pass data through parameters and return values.
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(10, 20);
return 0;
}
Here:
mainis the caller.addis the callee.10and20are actual arguments.aandbare formal parameters.returnreturns the computed result to the caller.
For complex programs, the way data is passed between functions directly affects the degree of coupling between modules.
III. Execution Mechanism of Procedural Programming
To understand procedural programming, one cannot stop at function definitions and calls; one also needs to understand control flow, the call stack, and data storage during program execution.
1. Program Execution Flow
A typical procedural program starts executing from the entry function and continuously enters different execution processes according to function call relationships.
Taking C as an example:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int multiply(int a, int b) {
return a * b;
}
int main() {
int x = add(10, 20);
int y = multiply(x, 2);
printf("%d\n", y);
return 0;
}
Execution process:
flowchart TD
A["Enter main function"] --> B["Call add(10, 20)"]
B --> C["Calculate a + b"]
C --> D["Return 30"]
D --> E["Call multiply(30, 2)"]
E --> F["Calculate a * b"]
F --> G["Return 60"]
G --> H["Output result"]
H --> I["End main function"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. Function Call Stack (Call Stack)
Function calls usually involve the call stack.
When a function is called, the runtime environment needs to save the current execution position and manage the necessary execution state for the called function.
A typical call process involves:
- Return address.
- Function parameters.
- Local variables.
- Saved register state.
- Other information needed by the compiler or runtime.
This information is usually managed through a stack frame (Stack Frame).
For example:
void c() {
int x = 10;
}
void b() {
c();
}
void a() {
b();
}
int main() {
a();
return 0;
}
Function call relationships:
flowchart TD
A["main()"] --> B["a()"]
B --> C["b()"]
C --> D["c()"]
D --> E["c() returns"]
E --> F["b() returns"]
F --> G["a() returns"]
G --> H["main() continues execution"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
From a runtime perspective, function calls have a clear nested relationship.
After c() finishes executing, the program returns to the call site in b(); after b() finishes, it returns to a().
Note the following:
- The call stack is a common implementation for managing function execution state.
- Not all languages must use a traditional machine stack to implement function calls.
- Compilers may perform inlining, tail-call optimization, or other optimizations.
- Local variables are also not necessarily all actually stored in stack memory; this depends on compiler optimizations and runtime implementation.
3. Global Data and Local Data
In procedural programs, data is usually organized by scope and storage duration.
#include <stdio.h>
int global_count = 0;
void increment() {
int local_count = 1;
global_count++;
printf("%d %d\n", local_count, global_count);
}
Here:
global_count: a file-scope variable with static storage duration.local_count: a block-scope local variable, usually with automatic storage duration.
Differences between the two:
| Comparison | Global variable | Local variable |
|---|---|---|
| Definition location | Outside functions | Inside a function or code block |
| Visibility | Affected by declaration location and linkage attributes | Usually limited to the containing code block |
| Storage duration | Usually static storage duration | Usually automatic storage duration |
| Lifetime | Usually throughout program execution | Usually tied to the containing execution block |
| Main risks | Global state coupling, data races | Access outside scope, lifetime issues |
Global variables make it convenient to share state, but they also increase implicit dependencies between functions.
For example, if one function modifies a global variable, another function may be affected without knowing it.
This is also one of the reasons large procedural programs are prone to complex state management problems.
IV. Typical Design Approaches in Procedural Programming
Procedural programming usually adopts a top-down program design method.
That is, first analyze the entire problem, then gradually break it down into multiple subproblems, and finally implement the subproblems as functions.
1. Top-Down Design
Suppose we need to develop a student grade management program.
First analyze the overall functionality:
- Add students.
- Query students.
- Calculate average grades.
- Output grade reports.
Then further break down each function:
Grade Management System
├── Student Management
│ ├── Add Student
│ ├── Delete Student
│ └── Query Student
├── Grade Processing
│ ├── Enter Grades
│ ├── Calculate Average Score
│ └── Calculate Highest Score
└── Report Output
├── Output Student Information
└── Generate Grade Report
Program design process:
flowchart TD
A["Analyze the overall problem"] --> B["Divide into main functions"]
B --> C["Break down sub-functions"]
C --> D["Define function interfaces"]
D --> E["Implement each function"]
E --> F["Compose function calls"]
F --> G["Integration testing"]
G --> H{"Does it meet requirements?"}
H -->|"No"| I["Locate and fix issues"]
I --> E
H -->|"Yes"| J["Complete the program"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
2. Structured Programming
Structured programming is closely related to procedural programming.
It emphasizes organizing programs through clear control structures and avoiding unstructured jumps, so that programs have execution logic that is easier to understand and verify.
Classic control structures in structured programming include:
- Sequence structure.
- Selection structure.
- Loop structure.
These three basic control structures can express general algorithmic control logic.
For example:
int calculate_sum(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
Here, a loop structure is used to perform the accumulation, rather than organizing the execution process through a large number of unconditional jumps.
3. Modularization and Function Decomposition
Procedural programs can be further modularized through functions and files.
For example:
student_system/
├── main.c
├── student.c
├── student.h
├── score.c
├── score.h
├── report.c
└── report.h
Here:
student.c: implements student information management.score.c: implements score processing.report.c: implements report output..hfiles: declare the interfaces exposed by the module.main.c: is responsible for the program entry point and overall flow organization.
In C, header files are usually used to declare functions, types, and macros, while source files are responsible for implementing functions. Together with the compilation and linking mechanisms, they form program modules.
Note: file partitioning in C does not automatically create enforced access-control boundaries. Mechanisms such as static, header-file declarations, and linkage attributes can further control symbol visibility.
V. A Complete Example of Procedural Programming
Using student score management as an example, this shows how to organize a small program in a procedural way.
1. Requirements Analysis
The system needs to implement:
- Enter student scores.
- Calculate the average score.
- Obtain the highest score.
- Output statistical results.
2. Data Structure Design
Use a struct to represent student information:
typedef struct {
char name[32];
float score;
} Student;
Use an array to store multiple students:
Student students[100];
3. Function Design
Split the system into multiple functions:
| Function | Responsibility |
|---|---|
input_students() |
Record student information |
calculate_average() |
Calculate average score |
find_max_score() |
Get highest score |
print_report() |
Output statistical report |
4. Complete Code
#include <stdio.h>
#define MAX_STUDENTS 100
typedef struct {
char name[32];
float score;
} Student;
void input_students(Student students[], int count) {
for (int i = 0; i < count; i++) {
printf("请输入姓名和成绩:");
scanf("%31s %f", students[i].name, &students[i].score);
}
}
float calculate_average(Student students[], int count) {
if (count <= 0) {
return 0.0f;
}
float sum = 0.0f;
for (int i = 0; i < count; i++) {
sum += students[i].score;
}
return sum / count;
}
float find_max_score(Student students[], int count) {
if (count <= 0) {
return 0.0f;
}
float max_score = students[0].score;
for (int i = 1; i < count; i++) {
if (students[i].score > max_score) {
max_score = students[i].score;
}
}
return max_score;
}
void print_report(Student students[], int count) {
printf("\n学生成绩报告\n");
for (int i = 0; i < count; i++) {
printf("%s: %.2f\n",
students[i].name,
students[i].score);
}
printf("平均成绩: %.2f\n",
calculate_average(students, count));
printf("最高成绩: %.2f\n",
find_max_score(students, count));
}
int main() {
Student students[MAX_STUDENTS];
int count;
printf("请输入学生人数:");
scanf("%d", &count);
if (count <= 0 || count > MAX_STUDENTS) {
printf("学生人数不合法\n");
return 1;
}
input_students(students, count);
print_report(students, count);
return 0;
}