CurriculumFunctions
Functions
Functions allow you to encapsulate a piece of code, give it a name, and reuse it multiple times. They are the building blocks of any non-trivial C++ program. In this lesson, we will cover function basics, parameter passing, overloading, and the inline keyword.
01Basic Functions
A function has a return type, a name, and parameters.
If a function doesn't return anything, its return type is
If a function doesn't return anything, its return type is
void. Execution always starts at main(), which calls other functions.main.cpp
Terminal
Waiting for execution...
Visualizer
Click Run to see memory state
02Pass by Value
By default, C++ passes arguments by value. This means the function gets a copy of the variable, not the original one.
Look closely at this example: modifying
Look closely at this example: modifying
x inside the function does not modify score in main.main.cpp
Terminal
Waiting for execution...
Visualizer
Run code to see stack and heap.
03Default Arguments
You can provide default values for parameters. If the caller doesn't provide an argument, the compiler uses the default.
Rule: Default arguments must be placed at the end of the parameter list.
Rule: Default arguments must be placed at the end of the parameter list.
main.cpp
Terminal
Waiting for execution...
04Function Overloading
C++ allows multiple functions to have the exact same name, as long as their parameters are different (different types or different number of parameters).
The compiler figures out which one to call based on the arguments you pass. This is called function overloading.
The compiler figures out which one to call based on the arguments you pass. This is called function overloading.
main.cpp
Terminal
Waiting for execution...
05Inline Functions (Pro Tip)
Calling a function has a small performance overhead (pushing to the stack, jumping memory addresses).
For very small functions, you can use the
For very small functions, you can use the
inline keyword. It asks the compiler to replace the function call with the actual code body, saving the overhead. (Modern compilers often do this automatically during optimization).main.cpp
Terminal
Waiting for execution...
AI Tutor
Without functions, your code would be a massive, unreadable, unmaintainable single block in main(). Functions provide structure, reusability, and testability.