Writing your first custom function
What you'll learn: How to group a set of instructions into a named, reusable block of code to keep your programs organized.
The Recipe Box Analogy
Think of a function as a recipe card in a kitchen. Up until now, you have been writing all your code inside the main function—like one giant, messy scroll of instructions. A custom function allows you to take a specific task, name it, and store it separately. When you need that task done, you simply "call" its name, and the program jumps to those instructions, finishes them, and comes right back to where it left off.
Defining Your Function
To create a function, you need three main parts:
- The Return Type: What kind of data does the function give back? For a simple action that just prints text, we use
void(which means "nothing"). - The Name: Use a descriptive name that sounds like an action (e.g.,
sayHello). - The Body: The actual code inside curly braces
{ }.
Here is how you write a simple function and use it inside your main program:
#include <stdio.h>
// 1. We define the function here
void greetUser() {
printf("Hello there!\n");
printf("Welcome to your first custom function.\n");
}
int main() {
printf("Starting the program...\n");
// 2. We "call" the function by its name
greetUser();
printf("Back in main!");
return 0;
}
How the Computer Reads This
When the program runs, it starts inside main. When it hits the line greetUser();, the computer pauses what it's doing in main and looks for the block of code labeled greetUser. It runs the two printf statements inside that block. Once it reaches the closing brace }, it "returns" to main and continues with the next line of code.
Why Bother?
If you wanted to greet the user ten times, you wouldn't need to copy and paste the printf lines over and over. You would simply call greetUser(); ten times. This makes your code much easier to read and allows you to fix a bug in one single place instead of hunting through hundreds of lines of code.
Key takeaway
Functions are named containers for code that perform a specific task, allowing you to reuse logic without retyping it.