Introduction & Syntax
Functions and Default Arguments · Study material
Functions in C++ break a program into named, reusable pieces. A function takes parameters, does one job and returns a result – and C++ gives you far more control over this than C: parameters by value, by reference or by const reference, default arguments, function overloading, returning several values with structured bindings or std::optional, constexpr functions that run at compile time, and function objects stored in std::function. Pass-by-reference, overload resolution and recursion are among the most asked C++ interview topics. This page explains them all with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.
On this page
- Declaring, defining and calling functions; prototypes
- Pass by value, by reference, by const reference and by pointer
- Returning values: structs, pair, tuple, structured bindings, std::optional
- Default arguments and function overloading (and how calls are resolved)
- Recursion, static local variables, inline, constexpr and consteval
- noexcept, [[nodiscard]], auto return types, function pointers and std::function
Declaring, defining and calling a function
A function definition has a return type, a name, a parameter list and a body. A declaration (prototype) is the same without the body, ending in a semicolon; it lets you call a function that is defined later or in another file. Header files are mostly collections of declarations. A function that returns nothing has return type void.
#include <iostream>
double area(double length, double width); // declaration (prototype): name, parameters, return type
int main() {
std::cout << area(4, 2.5) << '\n'; // call: arguments are copied into the parameters
std::cout << area(10, 10) << '\n';
return 0;
}
double area(double length, double width) { // definition: the body
return length * width;
}
10 100
Passing arguments
How a parameter is declared decides whether the function gets a copy or access to the caller's object:
| Parameter | Function gets | Can change caller's variable? | Use for |
|---|---|---|---|
int x | a copy | no | small, cheap types |
int& x | an alias of the argument | yes | "out" parameters, modifying in place |
const T& x | a read-only alias, no copy | no | strings, vectors, large objects |
int* x | an address (may be nullptr) | yes, through *x | optional arguments, C APIs |
#include <iostream>
#include <string>
void by_value(int x) { x += 10; } // works on a copy
void by_reference(int& x) { x += 10; } // works on the caller's variable
void by_pointer(int* x) { if (x) *x += 10; } // works through the address (may be null)
std::size_t length(const std::string& s) { return s.size(); } // no copy, read-only
int main() {
int a = 1, b = 1, c = 1;
by_value(a);
by_reference(b);
by_pointer(&c);
std::cout << a << ' ' << b << ' ' << c << '\n';
std::cout << length("temporary strings are fine") << '\n'; // const& binds to temporaries
return 0;
}
1 11 11 26
A non-const reference can only bind to a variable (an lvalue) – by_reference(5) does not compile – while a const& also accepts temporaries and literals.
Returning values
return ends the function and hands back a value. To return several values, return a struct (best: named fields), a std::pair or a std::tuple, and unpack it with structured bindings auto [a, b] = f();. For "a value or nothing" return std::optional. Never return a reference or pointer to a local variable – it is destroyed when the function returns.
#include <iostream>
#include <optional>
#include <tuple>
#include <utility>
#include <vector>
struct Stats { int min, max; double average; };
Stats stats(const std::vector<int>& v) { // a struct with named fields
int lo = v[0], hi = v[0];
long long sum = 0;
for (int x : v) { lo = std::min(lo, x); hi = std::max(hi, x); sum += x; }
return {lo, hi, static_cast<double>(sum) / v.size()};
}
std::pair<int, int> divide(int a, int b) { return {a / b, a % b}; }
std::optional<std::size_t> find(const std::vector<int>& v, int target) { // "maybe a value"
for (std::size_t i = 0; i < v.size(); ++i)
if (v[i] == target) return i;
return std::nullopt;
}
int main() {
std::vector<int> marks{72, 95, 61, 88};
auto [lo, hi, avg] = stats(marks); // structured bindings (C++17)
auto [q, r] = divide(17, 5);
std::cout << lo << ' ' << hi << ' ' << avg << " | " << q << ' ' << r << '\n';
if (auto pos = find(marks, 88)) std::cout << "88 at index " << *pos << '\n';
std::cout << "50 found: " << find(marks, 50).has_value() << '\n';
return 0;
}
61 95 79 | 3 2 88 at index 3 50 found: 0
Default arguments
A default argument is used when the caller leaves it out. Defaults must be the rightmost parameters, and are written once – normally in the declaration, not repeated in the definition. The default value is evaluated at each call.
#include <iostream>
#include <string>
// Defaults go from the right: every parameter after a defaulted one must have a default too
std::string greet(const std::string& name, const std::string& greeting = "Hello", char end = '!') {
return greeting + ", " + name + end;
}
int main() {
std::cout << greet("Asha") << '\n';
std::cout << greet("Ravi", "Welcome") << '\n';
std::cout << greet("Meera", "Hi", '.') << '\n';
return 0;
}
Hello, Asha! Welcome, Ravi! Hi, Meera.
Function overloading
Several functions may share a name if their parameter lists differ in number or types – compile-time polymorphism. The compiler picks the best match: an exact match beats a promotion (char/short → int, float → double), which beats a standard conversion (int → double). If two candidates are equally good, the call is ambiguous and does not compile. The return type alone cannot distinguish overloads.
#include <iostream>
#include <string>
void show(int x) { std::cout << "int " << x << '\n'; }
void show(double x) { std::cout << "double " << x << '\n'; }
void show(const std::string& s) { std::cout << "string " << s << '\n'; }
void show(int a, int b) { std::cout << "two ints " << a + b << '\n'; }
int main() {
show(7); // exact match: int
show(2.5); // exact match: double
show(3.5f); // float → double is a promotion, better than float → int
show('A'); // char → int is a promotion
show(std::string("C++"));
show(2, 3); // different number of parameters
return 0;
}
int 7 double 2.5 double 3.5 int 65 string C++ two ints 5
| Rank | Conversion | Example |
|---|---|---|
| 1. Exact match | identical type, array/function to pointer, adding const | int → int |
| 2. Promotion | char/short/bool → int, float → double | 'A' → int |
| 3. Conversion | int ↔ double, int → long, derived* → base* | 5 → double |
| 4. User-defined | constructors, conversion operators | "abc" → std::string |
Recursion
A recursive function calls itself on a smaller problem. It needs a base case that stops the recursion, and every call must move toward it. Each call gets its own copies of parameters and locals on the call stack, so very deep recursion can overflow the stack – loops or memoization are often better for large inputs.
#include <iostream>
long long factorial(int n) {
if (n <= 1) return 1; // base case stops the recursion
return n * factorial(n - 1); // recursive case moves toward it
}
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } // Euclid
void countdown(int n) {
if (n == 0) { std::cout << "go!\n"; return; }
std::cout << n << ' ';
countdown(n - 1);
}
int main() {
std::cout << factorial(10) << ' ' << factorial(20) << '\n';
std::cout << gcd(84, 36) << '\n';
countdown(3);
return 0;
}
3628800 2432902008176640000 12 3 2 1 go!
Static local variables
A static local variable is initialized once – the first time control passes through its declaration – and keeps its value between calls. Its initialization is thread-safe since C++11.
#include <iostream>
int next_ticket() {
static int counter = 100; // initialized once, keeps its value between calls
return ++counter;
}
int calls() {
int local = 0; // created fresh on every call
return ++local;
}
int main() {
std::cout << next_ticket() << ' ' << next_ticket() << ' ' << next_ticket() << '\n';
std::cout << calls() << ' ' << calls() << '\n';
return 0;
}
101 102 103 1 1
inline, constexpr and consteval
inline today mainly means "this function may be defined in several translation units" (so it can live in a header); whether the call is actually expanded is up to the optimizer. A constexpr function can be evaluated at compile time when its arguments are constants, and at run time otherwise. A C++20 consteval function must be evaluated at compile time.
#include <iostream>
constexpr long long power(long long base, int exp) { // usable at compile time AND run time
long long result = 1;
while (exp-- > 0) result *= base;
return result;
}
consteval int kilobytes(int n) { return n * 1024; } // C++20: must run at compile time
int main() {
constexpr long long big = power(2, 40); // computed by the compiler
static_assert(power(3, 4) == 81); // checked while compiling
int buffer[kilobytes(1) / 256]{}; // 4 elements, size known at compile time
int e;
std::cin >> e;
std::cout << big << ' ' << sizeof(buffer) / sizeof(int) << ' ' << power(5, e) << '\n'; // run time
return 0;
}
3
1099511627776 4 125
noexcept, [[nodiscard]] and return-type deduction
// noexcept: promises not to throw – lets the library use faster code paths (e.g. moving in std::vector)
int safe_add(int a, int b) noexcept { return a + b; }
// [[nodiscard]]: the compiler warns if a caller ignores the result
[[nodiscard]] bool save(const std::string& file);
save("data.txt"); // warning: ignoring return value
// auto return type: deduced from the return statement
auto half(double x) { return x / 2; } // returns double
// trailing return type: the type is written after the parameters
auto max_of(int a, int b) -> int { return a > b ? a : b; }
Function pointers and std::function
A function's name converts to a pointer to it, so functions can be passed to other functions (callbacks). std::function<R(Args…)> from <functional> is a general wrapper that holds any callable with that signature – plain functions, lambdas with captures, function objects.
#include <functional>
#include <iostream>
#include <vector>
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int apply(int (*op)(int, int), int a, int b) { return op(a, b); } // classic function pointer
int main() {
std::cout << apply(add, 6, 7) << ' ' << apply(mul, 6, 7) << '\n';
int offset = 100;
std::vector<std::function<int(int, int)>> ops{add, mul,
[offset](int a, int b) { return a + b + offset; }}; // std::function also holds lambdas
for (const auto& op : ops)
std::cout << op(2, 3) << ' ';
std::cout << '\n';
return 0;
}
13 42 5 6 105
Common mistakes
- Expecting by-value parameters to change the caller's variable – use a reference.
- Passing big objects by value –
void f(std::vector<int> v)copies the whole vector; useconst&. - Returning a reference to a local – a dangling reference and undefined behaviour.
- Missing base case – infinite recursion ends in a stack overflow.
- Ambiguous overloads –
f(int)andf(long)called with a double does not compile. - Repeating default arguments in both declaration and definition is an error.
- Forgetting return in a non-void function is undefined behaviour – enable warnings.
Key points to remember
- By value copies; by reference aliases; const& reads without copying.
- Return several values with a struct, pair or tuple and structured bindings.
- Default arguments must be the rightmost parameters.
- Overloads differ by parameters, never only by return type.
- Recursion needs a base case; static locals keep their value between calls.
- constexpr may run at compile time; consteval must.
Frequently asked questions
When should I pass by reference in C++?
When the function must modify the caller's object (T&), or when the object is expensive to copy and only read (const T&). Small types such as int, double and pointers are best passed by value.
What is the difference between overloading and default arguments?
Default arguments give one function optional parameters with fixed fallback values; overloading provides separate functions that may behave differently for different parameter types or counts.
Is recursion slower than loops?
Each call has some overhead and uses stack space, so a loop is usually a little faster. Recursion is clearer for naturally recursive problems such as trees, divide and conquer and backtracking.
Where can I learn more?
Read C++ Functions and C++ Lambda Expressions, then practise with the exercises below.