Modern C++ • C++20 baseline
Functions, Parameters, and Return Values
Design functions around clear inputs, outputs, and ownership.
Pass small scalar values by value. Pass larger read-only objects by const reference when copying would be wasteful, and return values by value for ordinary results—the compiler can elide or move many such returns. Use output parameters only when they materially improve the interface or are needed for multiple results.
Key points
- A function signature is a small contract for callers.
- Avoid non-const reference parameters when a function does not modify the argument.
Example
#include <string>
std::string greeting(const std::string& name) {
return "Hello, " + name;
}
What to expect
greeting("Riya") returns the string “Hello, Riya”.
Practice exercise
Add validation for an empty name and choose whether the function should return a fallback or report an error.
Key idea: Make mutation and failure visible in the function interface.