So far, all our programs have lived inside a single main(). That works for 20 lines, but real programs have thousands. If the same task (say, checking whether a number is prime) is needed in five places, copying the same loop five times is a recipe for bugs: fix one copy and forget the others.
A function lets you write a piece of logic once, give it a name, and use it as many times as you like.
A function is a named, self-contained block of code that performs a specific task. It can take input values (parameters), and it can give back a result (return value).
You have already been using functions: main() is one, and the standard library is full of them. In this chapter you will learn to write your own, and to understand exactly what happens when one function calls another.
Why functions matter:
Reuse: write once, call many times.
Readability:
if (isPrime(n))explains itself; a nested loop does not.Divide and conquer: a big problem becomes several small, testable pieces.
Easier fixing: a bug in
isPrimeis fixed in one place, for every caller.
Anatomy of a Function
return_type function_name ( parameter_list )
{
// body
return value; // if return_type is not void
}
#include <iostream>
// Function definition: return type, name, parameter list, body
int square(int x) {
return x * x;
}
int main() {
std::cout << square(5) << '\n';
std::cout << square(12) << '\n';
int side = 7;
int area = square(side); // the returned value can be stored
std::cout << "Area = " << area << '\n';
}
Output:
25
144
Area = 49
Part | In the example | Meaning |
|---|---|---|
Return type |
| Type of the value the function gives back ( |
Name |
| Used to call the function; follows identifier rules |
Parameter list |
| Variables that receive the input; may be empty |
Body |
| The statements that do the work |
Return statement |
| Ends the function and sends a value back to the caller |
Parameters vs Arguments
These two words are often mixed up, and interviewers like to check:
A parameter (formal parameter) is the variable in the function definition:
xinint square(int x).An argument (actual argument) is the value you pass in the call:
5,12orsideinsquare(side).
When the function is called, each parameter is initialized from the matching argument.
Declaration vs Definition
The C++ compiler reads your file from top to bottom. A function must be declared before it is called, otherwise the compiler has no idea what the name means:
#include <iostream>
int main() {
std::cout << cube(3) << '\n';
}
int cube(int x) { return x * x * x; }
error: 'cube' was not declared in this scope
One fix is to define the function above main(). The other is to write a declaration (also called a prototype) near the top, and the full definition anywhere later:
#include <iostream>
// Declarations (prototypes): tell the compiler these functions exist
int maxOf(int a, int b);
void printLine(int length);
int main() {
printLine(20);
std::cout << "max(17, 42) = " << maxOf(17, 42) << '\n';
printLine(20);
}
// Definitions: can come later in the file
int maxOf(int a, int b) {
return (a > b) ? a : b;
}
void printLine(int length) {
for (int i = 0; i < length; ++i) {
std::cout << '-';
}
std::cout << '\n';
}
Output:
--------------------
max(17, 42) = 42
--------------------
Declaration (prototype) | Definition | |
|---|---|---|
Looks like |
|
|
Has a body? | No, ends with | Yes |
Parameter names | Optional: | Needed if the body uses them |
How many allowed | Many (all must agree) | Exactly one in the whole program (the One Definition Rule) |
Job | Tells the compiler the name, return type and parameter types | Provides the actual code |
This split is what makes multi-file programs possible: declarations go in a header file (.h/.hpp) that every .cpp file includes, and each definition lives in exactly one .cpp file. If you declare a function but never define it, compilation succeeds but linking fails:
undefined reference to `cube(int)'
collect2: error: ld returned 1 exit status
Learn to recognise the difference: "not declared in this scope" is a compiler error (missing declaration); "undefined reference" is a linker error (missing definition).
The return Statement
return does two things: it ends the function immediately and (for non-void functions) hands a value back to the caller. The value is converted to the declared return type if needed.
void Functions and Early Return
A function that does a job but has nothing to give back uses void. It may still use a plain return; to leave early:
#include <iostream>
void printGrade(int marks) {
if (marks < 0 || marks > 100) {
std::cout << marks << ": invalid marks\n";
return; // leave the function early
}
if (marks >= 40)
std::cout << marks << ": pass\n";
else
std::cout << marks << ": fail\n";
}
int main() {
printGrade(73);
printGrade(25);
printGrade(120);
}
Output:
73: pass
25: fail
120: invalid marks
return Inside a Loop
Remember the prime check from Break & Continue? As a function, it becomes shorter, because return leaves the loop and the function at once. No flag variable is needed:
#include <iostream>
bool isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; ++d) {
if (n % d == 0) return false; // return ends the loop AND the function
}
return true;
}
int main() {
std::cout << "Primes below 30: ";
for (int i = 1; i < 30; ++i) {
if (isPrime(i)) std::cout << i << ' ';
}
std::cout << '\n';
}
Output:
Primes below 30: 2 3 5 7 11 13 17 19 23 29
Forgetting to Return a Value (Undefined Behaviour)
int sign(int x) {
if (x > 0) return 1;
if (x < 0) return -1;
} // x == 0 falls off the end: undefined behaviour
This compiles, with only a warning:
warning: control reaches end of non-void function [-Wreturn-type]
If sign(0) is ever called, control reaches the closing brace of a non-void function without a return. In C++ that is undefined behaviour: the program may return garbage, crash, or behave strangely in optimized builds. Every path through a non-void function must return a value. The single exception is main(): reaching its end is the same as return 0;.
Pass by Value
By default, C++ passes arguments by value: each parameter is a brand new local variable initialized with a copy of the argument. Changing the parameter does not touch the caller's variable.
#include <iostream>
void tryToChange(int n) {
n = 100; // changes the local copy only
std::cout << "inside : n = " << n << '\n';
}
void swapValues(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int n = 5;
tryToChange(n);
std::cout << "outside: n = " << n << '\n';
int x = 1, y = 2;
swapValues(x, y);
std::cout << "after swapValues: x = " << x << ", y = " << y << '\n';
}
Output:
inside : n = 100
outside: n = 5
after swapValues: x = 1, y = 2
main's frame swapValues' frame
┌─────────┐ copy → ┌─────────┐
│ x = 1 │ ────────────→ │ a = 1→2 │ swapped here...
│ y = 2 │ ────────────→ │ b = 2→1 │
└─────────┘ └─────────┘
unchanged ...and destroyed on return
Pass by value is safe (a function cannot accidentally damage your variables) and ideal for small types like int, double and char. But it has two limits: the function cannot change the caller's variables (so swapValues fails), and copying large objects costs time. C++ solves both with pass by reference (void swap(int& a, int& b)), covered in detail in the References chapter, and C-style pass by pointer, covered in Pointers.
What Happens During a Function Call: The Call Stack
Each time a function is called, the program creates a stack frame (activation record) for it on the call stack. The frame holds the function's parameters, local variables and the return address (where to continue in the caller). When the function returns, its frame is removed. Last called, first finished: a stack.
#include <iostream>
int addTax(int price) {
std::cout << " addTax(" << price << ") starts\n";
int result = price + price * 18 / 100;
std::cout << " addTax returns " << result << '\n';
return result;
}
int billFor(int qty, int unitPrice) {
std::cout << " billFor(" << qty << ", " << unitPrice << ") starts\n";
int total = addTax(qty * unitPrice);
std::cout << " billFor returns " << total << '\n';
return total;
}
int main() {
std::cout << "main starts\n";
int bill = billFor(3, 200);
std::cout << "main got " << bill << '\n';
}
Output:
main starts
billFor(3, 200) starts
addTax(600) starts
addTax returns 708
billFor returns 708
main got 708
At the deepest point, the stack looks like this (top = currently running):
┌──────────────────────────────┐ ← top
│ addTax: price = 600 │
│ result = 708 │
├──────────────────────────────┤
│ billFor: qty = 3 │
│ unitPrice = 200 │
├──────────────────────────────┤
│ main: bill = ? │
└──────────────────────────────┘
This picture explains several rules at once: local variables of different functions never clash (each lives in its own frame), they disappear when the function returns, and calling functions has a small cost (creating and removing frames). It is also the key to understanding Recursion, coming up a few chapters later.
Scope and Lifetime of Variables
Scope is where in the code a name can be used. Lifetime (storage duration) is how long the variable actually exists while the program runs.
Kind | Declared | Scope | Lifetime |
|---|---|---|---|
Local (automatic) | Inside a function or block | From declaration to end of block | Created each time the block runs, destroyed at its end |
Parameter | In the parameter list | Whole function body | Same as a local variable of the function |
| Inside a function, with | From declaration to end of block | Initialized once (the first time control passes its declaration), lives until the program ends |
Global | Outside all functions | From declaration to end of file | Whole program |
Local Names Hide Global Names
#include <iostream>
int value = 10; // global variable
void show() {
int value = 20; // local: hides the global inside show()
std::cout << "local value = " << value << '\n';
std::cout << "global value = " << ::value << '\n';
}
int main() {
show();
std::cout << "in main value = " << value << '\n';
}
Output:
local value = 20
global value = 10
in main value = 10
The scope resolution operator :: with nothing on its left means "the name from the global scope". Even so, avoid global variables where you can: any function can change them, which makes bugs hard to trace. Passing values through parameters and return values keeps data flow visible.
static Local Variables
A static local variable keeps its value between calls, while still being visible only inside its function:
#include <iostream>
int nextTicket() {
static int counter = 0; // initialized only once
int normal = 0; // created fresh on every call
++counter;
++normal;
std::cout << "counter = " << counter << ", normal = " << normal << '\n';
return counter;
}
int main() {
nextTicket();
nextTicket();
nextTicket();
}
Output:
counter = 1, normal = 1
counter = 2, normal = 1
counter = 3, normal = 1
counter is not stored in the stack frame; it lives in static storage for the whole program run, so it survives each return. Since C++11, the initialization of a static local is also guaranteed to be thread-safe.
Modern Function Features
auto Return Type (C++14) and Trailing Return Type (C++11)
#include <iostream>
auto average(int a, int b) { // C++14: return type deduced as double
return (a + b) / 2.0;
}
auto cube(int x) -> long long { // C++11: trailing return type
return 1LL * x * x * x;
}
int main() {
std::cout << average(4, 7) << '\n';
std::cout << cube(2000) << '\n';
}
Output:
5.5
8000000000
With auto alone, the compiler deduces the return type from the return statements (all of them must deduce the same type). With auto f(...) -> T, the type is simply written after the parameters; this is mostly useful in templates. Note the 1LL * in cube: without it, x * x * x would be computed in int and overflow (undefined behaviour) before being converted to long long.
constexpr (C++11) and consteval (C++20) Functions
A constexpr function can be evaluated by the compiler when its arguments are compile-time constants, and also works as a normal function at run time. C++11 allowed only a single return statement; C++14 relaxed the rules to allow loops and local variables. A consteval function (C++20) must be evaluated at compile time.
#include <iostream>
constexpr long long factorial(int n) { // C++14 rules allow loops here
long long result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
consteval int kilobytes(int n) { // C++20: must run at compile time
return n * 1024;
}
int main() {
constexpr long long f10 = factorial(10); // computed by the compiler
static_assert(factorial(5) == 120); // checked while compiling
int n = 6;
std::cout << f10 << '\n';
std::cout << factorial(n) << '\n'; // also works at run time
std::cout << kilobytes(4) << '\n';
}
Output:
3628800
720
4096
static_assert checks a condition while compiling; if factorial were wrong, the program would not even build. (The single-argument form of static_assert used here needs C++17.) Calling kilobytes(n) with a run-time variable would be a compile error, because consteval forbids run-time calls.
[[nodiscard]] (C++17)
Some results should never be ignored (an error code, a computed price). Marking the function [[nodiscard]] asks the compiler to warn when a caller throws the result away:
#include <iostream>
[[nodiscard]] int computeDiscount(int price) {
return price / 10;
}
int main() {
computeDiscount(500); // result ignored: warning
int d = computeDiscount(500);
std::cout << "Discount: " << d << '\n';
}
Compiler warning:
warning: ignoring return value of 'int computeDiscount(int)', declared with attribute 'nodiscard' [-Wunused-result]
Output:
Discount: 50
Order of Evaluation of Arguments
In the call add(show(1), show(2)), which argument is evaluated first? C++ does not say. The order is unspecified: each compiler may choose, and may even choose differently in different places.
#include <iostream>
int show(int x) {
std::cout << "evaluating " << x << '\n';
return x;
}
int add(int a, int b) {
return a + b;
}
int main() {
int sum = add(show(1), show(2));
std::cout << "sum = " << sum << '\n';
}
Output (g++ 15 on x86-64 Linux):
evaluating 2
evaluating 1
sum = 3
g++ happened to evaluate the second argument first. Another compiler, or another platform, may print the lines in the other order. The sum is always 3, but any side effects (printing, modifying variables) may happen in either order. Since C++17, each argument is at least evaluated completely before the next one starts (they are "indeterminately sequenced", never interleaved). The rule for you: never write a call whose result depends on argument evaluation order, such as f(i++, i).
Common Mistakes
Calling a function before declaring it. Add a prototype above
main(), or define the function earlier.Prototype and definition that disagree (e.g.
int f(int);butint f(double) {...}). C++ treats these as two different functions, so you get an "undefined reference" link error for the one never defined.Missing
returnon some path of a non-void function: undefined behaviour. Treat-Wreturn-typeas an error.Expecting pass by value to change the caller's variable, as in
swapValues. Use references (see References).Ignoring the return value, e.g. calling
square(5);on its own line and expecting something to change.Defining a function inside another function. Standard C++ does not allow nested function definitions (lambdas, covered later, are the C++ way to write a small function inside another).
Depending on argument evaluation order: unspecified, so the program is not portable.
Interview and GATE Questions
Q1. What is the difference between a function declaration and a function definition?
A declaration (prototype) introduces the function's name, return type and parameter types, ending with a semicolon and no body. A definition also provides the body. A function may be declared many times but, under the One Definition Rule, a non-inline function must be defined exactly once in the program.
Q2. What is printed?
int f() {
static int x = 5;
return x--;
}
int main() {
std::cout << f() << ' ';
std::cout << f() << ' ';
std::cout << f() << '\n';
}
int f() {
static int x = 5;
return x--;
}
int main() {
std::cout << f() << ' ';
std::cout << f() << ' ';
std::cout << f() << '\n';
}
5 4 3. x is initialized only once. Each call returns the current value and then decrements it (post-decrement). Three separate statements are used, so the order is well defined.
Q3. Is it OK for a function to return without a value if its return type is int?
int?No. Flowing off the end of a non-void function (other than main) is undefined behaviour in C++. It compiles with only a warning, so always enable warnings. main is special: reaching its end is equivalent to return 0;.
Q4. What is a stack frame and what does it contain?
A stack frame (activation record) is the block of memory created on the call stack for each function call. It typically holds the parameters, local (automatic) variables, the return address and saved registers. It is removed when the function returns, which is why local variables stop existing at that point. Static locals and globals are not stored in frames.
Q5. In f(a(), b()), is a() guaranteed to run before b()?
f(a(), b()), is a() guaranteed to run before b()?No. The order of evaluation of function arguments is unspecified in C++. Since C++17 the two calls cannot interleave, but either may run first.
Q6. What is the difference between constexpr and consteval functions?
constexpr and consteval functions?A constexpr function (C++11) may be evaluated at compile time when used in a constant expression, but can also be called normally at run time. A consteval function (C++20) is an "immediate function": every call must produce a compile-time constant, otherwise the program is ill-formed.
Summary
A function is a named block of code with a return type, a name, parameters and a body. Parameters are in the definition; arguments are in the call.
Declare before use. A prototype gives the signature; the definition gives the body. Missing declaration → compiler error; missing definition → linker error.
returnends the function and hands back a value. Falling off the end of a non-void function is undefined behaviour (exceptmain).Arguments are passed by value by default: the function works on copies. Use references to modify the caller's data.
Each call gets a stack frame; locals live only as long as the call.
staticlocals keep their value between calls.Modern extras:
autoreturn (C++14), trailing return (C++11),constexpr(C++11, relaxed in C++14),consteval(C++20),[[nodiscard]](C++17).Argument evaluation order is unspecified; never depend on it.
One function, one job, one clear name. Pass data in through parameters and get it out through the return value.