C Functions
The Vending Machine
Think of a function as a vending machine. You put in some coins (the arguments), press a button (the function call), and out comes a snack (the return value). You don't need to know what gears and motors spin inside β you just care about what goes in and what comes out.
In C, every program starts with one function: main(). From there, you break your code into smaller functions β each one doing one job well.
Anatomy of a Function
A C function has four parts:
- Return type β what kind of snack comes out (
int,float,char, orvoidfor nothing) - Name β the label on the button
- Parameters β the coin slots (what goes in)
- Body β the machinery inside
{ }
A Simple Math Function
Void Functions β No Snack Comes Out
Sometimes a vending machine doesn't give you a snack β it just does something (like playing music). A void function performs an action without returning a value. You can still use return; to exit early, but you don't return any data.
Void Functions
Function Prototypes β Declare Before You Use
C reads your file top to bottom. If main() calls a function that's defined below it, the compiler hasn't seen it yet and will complain. The fix? Put a prototype (also called a forward declaration) at the top. It's just the function signature followed by a semicolon β a promise that the full definition is coming later.
This is standard practice in C: prototypes at the top (or in a header file), definitions below main().
Function Prototypes
Pass-by-Value in Action
Why Break Code Into Functions?
Functions aren't just about avoiding repeated code (though that's a big win). They let you:
- Name a chunk of logic β
calculateTax(income)is clearer than 15 lines of math - Test pieces independently β you can verify
max()works without running the whole program - Divide work β different team members can write different functions
- Limit scope β variables inside a function can't leak out and cause confusion
Good C code is a collection of small, focused functions that each do one thing well.