Nearby lessons
71 of 124C - Function Introduction
A function is a named block of code that performs one job and can be called from anywhere. Learn why functions exist, the anatomy of a C function, and how main fits into the picture.
Why Functions Exist
Without functions, repeated logic must be copied. Here the same three lines appear twice — and would need fixing twice:
Example01
The Same Program with a Function
One definition, two calls. Fix a bug once and every caller benefits:
Example02
Anatomy of a Function
Every C function has the same five parts:
| Part | In int add(int a, int b) { return a + b; } | Purpose |
|---|---|---|
| Return type | int | The type of value sent back |
| Name | add | How callers refer to it |
| Parameters | (int a, int b) | The inputs it accepts |
| Body | { ... } | The work it does |
| Return statement | return a + b; | Sends the result to the caller |
Example03
How Control Flows
A call pauses the caller, runs the function, then resumes exactly where it left off. The print order proves it:
Example04
main Is a Function Too
In simple words:
main is not special syntax — it is an ordinary function that the operating system calls to start your program. Its return 0; reports success to the OS. Everything you learn about functions applies to main as well.Example05
Built-in and User-Defined
C ships with a standard library of ready-made functions; everything else you write yourself:
| Library functions | User-defined functions | |
|---|---|---|
| Who wrote them | The C standard library | You |
| How to use | #include the header | Define them in your file |
| Examples | printf, strlen, sqrt | add, calculateSalary |
| Source available | Usually not | Yes — it is yours |
Example06
What Functions Buy You
- Reusability — write once, call anywhere.
- Readability —
calculateTax(salary)explains itself; twenty inline lines do not. - Testability — a small function can be checked in isolation.
- Maintainability — one place to fix a bug.
- Teamwork — different people can own different functions.
- Abstraction — callers use the name and ignore the details.
Example07
One Function, One Job
The single most useful rule of function design: if you need "and" to describe what a function does, split it.
Example08
📝 Key Takeaways
- A function groups code under a name so it can be reused.
- Every C program starts execution at main().
- A function has a return type, a name, parameters and a body.
- Calling a function transfers control; return sends it back.
- Functions turn one long program into small testable pieces.
🧠 Test Your Knowledge
4 QuestionsProgress: 0 / 4