Coding Techniques
Functions and Default Arguments · Study material
Choose the parameter type by what the function does
Small types by value, large read-only objects by const reference, objects the function must change by reference. This one rule removes most accidental copies and most "why didn't my variable change?" bugs.
#include <iostream>
#include <string>
#include <vector>
// cheap to copy → by value; big or not copyable → const&; must modify → &
int square(int x) { return x * x; }
double average(const std::vector<double>& v) {
double s = 0;
for (double x : v) s += x;
return v.empty() ? 0 : s / v.size();
}
void add_suffix(std::string& s, const std::string& suffix) { s += suffix; }
int main() {
std::string file = "report";
add_suffix(file, ".pdf");
std::cout << square(12) << ' ' << average({2.5, 3.5, 6.0}) << ' ' << file << '\n';
return 0;
}
144 4 report.pdf
Return a struct instead of many out-parameters
// Hard to read: which argument is input, which is output?
void parse(const std::string& s, int& day, int& month, int& year, bool& ok);
// Clear: inputs are parameters, results are the return value
struct Date { int day, month, year; };
std::optional<Date> parse(const std::string& s);
if (auto d = parse("15-08-2026")) {
auto [day, month, year] = *d; // structured bindings
} Memoize expensive recursion
#include <unordered_map>
long long fib(int n) {
static std::unordered_map<int, long long> memo; // remembers results between calls
if (n < 2) return n;
if (auto it = memo.find(n); it != memo.end()) return it->second;
return memo[n] = fib(n - 1) + fib(n - 2);
}
// fib(90) returns instantly; the naive version would make ~10^18 calls Prefer overloading or templates to one function with a type flag
// Fragile: the caller must pass the right flag
double area(int shape, double a, double b = 0);
// Clear and checked by the compiler
double area(double radius) { return 3.141592653589793 * radius * radius; }
double area(double length, double width) { return length * width; } Good function habits
- One function, one job – and a name that says what it does.
- Keep functions short enough to read without scrolling.
- Pass large objects by
const&, return results by value (copy elision makes it cheap). - Mark functions that cannot throw
noexceptand results that must be used[[nodiscard]]. - Make pure computations
constexpr. - Write declarations in headers and definitions in .cpp files (except inline/templates).