Functions¶
Functions are the fundamental units of code organization in C++. They allow you to break down complex tasks into smaller, reusable pieces.
Declaration and Definition¶
- Declaration (Prototype): Tells the compiler about the function's name, return type, and parameters. Usually in header files (
.h). - Definition: The actual implementation of the function. Usually in source files (
.cpp).
Parameter Passing¶
How you pass data to functions matters for performance and safety.
1. Pass by Value¶
Creates a copy of the argument. Safe, but slow for large objects.
2. Pass by Reference (&)¶
Passes the original object. Fast (no copy), but allows modification.
3. Pass by Const Reference (const &)¶
The best of both worlds: fast (no copy) and safe (read-only). Use this for strings, vectors, and custom classes.
Passing Arrays (std::span) (C++20)¶
Historically, arrays were passed as a pointer and a size. This is unsafe. C++20 introduces std::span, a lightweight view into an array.
Discarded Return Values ([[nodiscard]])¶
If a function returns a value that should not be ignored (like an error code), mark it with [[nodiscard]]. The compiler will warn if the caller ignores it.
Function Overloading¶
You can have multiple functions with the same name, as long as their parameter lists differ.
Default Arguments¶
You can provide default values for parameters. They must be at the end of the parameter list.
inline Functions¶
The inline keyword suggests to the compiler to replace the function call with the function body itself. This can improve performance for small functions but increases binary size.
constexpr Functions¶
These functions can be evaluated at compile-time if given constant arguments. This is powerful for performance.
Return Type Deduction (auto) (C++14)¶
The compiler can deduce the return type from the return statement.