Functions
beginnerWhat you'll learn
- Break a task into small named functions.
- Pass data with parameters and return a result.
- Choose value, reference, or const-reference passing.
Functions are reusable blocks of code that perform a specific task.
Problem
A grade program must read marks, total them, average them, decide pass or fail, and print a report. Written as one long main(), it is hard to read and none of the logic can be reused.
Goal: Split the grade program into named tasks instead of one long main().
Break the work into named tasks instead:
main() readMarks() total() average() gradeOf() printReport()
Each task becomes a function: a reusable block with a name. Once you see why the pieces should be separate, the syntax below is just how you write one.
Why Use Functions?
- Avoid code duplication
- Make code readable and organized
- Easier to test and debug
- Break complex problems into smaller pieces
Function Syntax
Examples
The Call Stack
Each time a function is called, a new frame is pushed onto the call stack. When it returns, its frame is popped and control goes back to the caller.
Function Declaration vs Definition
Prototypes are placed before main(), definitions after main().
Scope
Always declare variables in the narrowest scope possible. Global variables make code hard to reason about and test.
Common mistakes: omitting the return statement in a non-void function, calling a function before its prototype is declared, and relying on global variables instead of parameters.
Key takeaway: Functions group reusable logic — declare prototypes before main(), define them after, and keep variables in narrow scopes.
Try it: Write a function int add(int a, int b) that returns the sum, then call it from main() and print the result.