Placement of functions in a file
What you'll learn: How the order of your code affects the compiler's ability to find and run your functions.
The "Top-Down" problem
Imagine you are reading a cookbook. If a recipe tells you to "zest the lemon" before it has explained what "zesting" is, you might be confused. The C compiler works the same way. It reads your file from the very first line down to the last.
If you call a function on line 10, but you don't actually define what that function does until line 20, the compiler will get nervous. It sees a name it doesn't recognize yet and might throw a warning or an error because it doesn't know if you're using the function correctly.
The two ways to organize
There are two common ways to handle this "order of operations" in your .c files.
1. The "Definition First" approach
You can place your custom functions physically above the main() function. This ensures that by the time the compiler reaches main(), it has already memorized how your other functions work.
#include <stdio.h>
// The compiler sees this first and remembers it
void say_hello() {
printf("Hello, Programmer!\n");
}
int main() {
say_hello(); // The compiler already knows what this is!
return 0;
}
2. The "Prototype" approach
Most professional code puts main() at the top because it’s the most important part of the program. To do this without confusing the compiler, we use a Function Prototype. This is a one-line "preview" at the top of the file that tells the compiler, "Hey, I'm going to use a function with this name later, so don't worry about it yet."
#include <stdio.h>
// A "preview" (prototype)
void say_hello();
int main() {
say_hello(); // Works because of the preview above
return 0;
}
// The actual details are hidden down here
void say_hello() {
printf("Hello, Programmer!\n");
}
Why placement matters
If you have a small script, putting functions at the top is easy. However, as your programs grow to include dozens of functions, using prototypes allows you to keep main()—the heart of your program—right at the top where it is easy to find, while tucking the technical details further down the page.
Key takeaway
C reads from top to bottom; always define a function or provide a "prototype" preview before you try to use it in your code.