Separating logic from main() for testability
What you'll learn: How to move your code into independent functions so you can verify they work correctly without running the entire program.
Imagine you are building a custom car. If you weld the engine, the battery, and the spark plugs directly to the car's frame, you can only test if the engine works by driving the whole car down the street. If it doesn't start, is it the battery? The fuel line? The tires? You have no way to know because everything is stuck together.
In C programming, putting all your code inside the main() function is like welding your engine to the frame. To make your code "testable," you need to keep your "engine" (the logic) separate from your "frame" (the user interface and program flow).
The "Everything in Main" Problem
When your logic lives in main(), it usually relies on printf() and scanf(). Automated testing tools find it very difficult to "read" a screen or "type" into a prompt. If you want to check if a tax calculation works for 100 different scenarios, you don't want to manually type 100 inputs into a running program.
The Solution: Pure Functions
To fix this, move the "thinking" parts of your code into their own functions. These functions should take inputs as parameters and return a result, without ever touching printf() or scanf().
Compare these two approaches for a simple discount calculator:
#include <stdio.h>
// WEAK: Hard to test because it's buried in main()
// and mixed with user input/output.
int main_old() {
float price = 100.0;
float discount = 0.2;
printf("Total: %f", price - (price * discount));
return 0;
}
// STRONG: Easy to test. This function doesn't care
// where the numbers come from.
float calculate_discount(float price, float percentage) {
if (price < 0) return 0;
return price - (price * percentage);
}
int main() {
// Now main() just handles the "plumbing"
float result = calculate_discount(100.0, 0.2);
printf("Result: %f\n", result);
return 0;
}
Why this helps
By extracting calculate_discount, you can now write a separate "test script"—another small C program—that calls that function with dozens of different numbers (like negative prices or 100% discounts) to see if it breaks. You can verify the logic in milliseconds without ever touching a keyboard or looking at a console.
Key takeaway
Keep your main() function thin by moving logic into standalone functions that take arguments and return values, making them easy to verify in isolation.