A function is a named block of code that does one job. You've been writing one all along: main. Now you'll write your own, so that each task in your program has a clear name and can be reused instead of copied.
C++ functions are typed: the first line says what type of value the function gives back and what types of values it needs. A function that calculates an area might take two double parameters and return a double. A function that only prints something returns void.
In this lesson you'll write and call functions, return values, give parameters default values, understand the difference between passing by value and by reference, and overload a function name.
Declaring and calling a function
int square(int n) {
return n * n;
}
int main() {
cout << square(6) << endl; // 36
}- The first word is the return type,
inthere. - Then the name and, in brackets, the parameters with their types.
returnsends a value back and ends the function.- A function must be declared above the code that calls it, or the compiler won't know it exists yet.
Use void as the return type for functions that don't return anything.
Prototypes
If you'd rather put main first, declare a prototype at the top: the function's first line followed by a semicolon. The full definition can then come later in the file:
double area(double w, double h); // prototype
int main() {
cout << area(3, 4);
}
double area(double w, double h) {
return w * h;
}In bigger projects, prototypes live in header files (.h) so that many .cpp files can use the same functions.
Pass by value and pass by reference
By default, C++ passes a copy of each argument. Changing the parameter inside the function doesn't affect the caller's variable.
Add & after the type to pass by reference. The parameter then becomes another name for the caller's variable, so changes are visible outside:
void addBonus(int& points) {
points += 10;
}References are also used to avoid copying large values. const string& name means "use the caller's string without copying it, and don't change it".
Default arguments and overloading
Give a parameter a default value and callers can leave it out:
void greet(string name, string greeting = "Hello") { ... }
greet("Ivy"); // Hello, Ivy
greet("Ivy", "Welcome"); // Welcome, IvyOverloading means writing several functions with the same name but different parameter types or counts. The compiler picks the version that matches the arguments you pass.
Scope, local variables and static locals
A variable declared inside a function is a local variable. It's created when that line runs and destroyed when the function ends, so every call starts afresh. Parameters work the same way. Two functions can each have a variable called total without any clash, because each one only exists inside its own braces.
Sometimes a function needs to remember something between calls. Adding static to a local variable makes it live for the whole program, while staying visible only inside that function:
int nextTicket() {
static int number = 0; // set to 0 once, the first time only
number++;
return number;
}Calling nextTicket() three times returns 1, 2 and then 3. Without static, number would be recreated as 0 on every call, and the function would always return 1.
Variables declared outside every function are global: any function in the file can read and change them. That sounds handy, but when something goes wrong, every function is a suspect. Prefer passing values in as parameters and returning results, and keep globals for true constants such as const double PI = 3.14159;.
C++ Functions Syntax
Function syntax
returnType name(Type a, Type b = defaultValue) {
return result;
}
void change(Type& ref); // pass by reference
void read(const Type& value); // no copy, read-onlyC++ Functions Summary
returnType name(Type param) { ... }defines a function; call it asname(arg).voidfunctions return nothing; others mustreturna value of their type.- Declare functions before use, or add a prototype at the top.
- Parameters are copies by default;
Type&passes a reference so changes stick. - Default arguments make parameters optional; overloading reuses a name.
C++ Functions Examples
Each example shows the code, the output it produces and what each part does.
Small, reusable functions
#include <iostream>
using namespace std;
double celsiusToFahrenheit(double c) {
return c * 9 / 5 + 32;
}
bool isFreezing(double c) {
return c <= 0;
}
void printReading(double c) {
cout << c << "C = " << celsiusToFahrenheit(c) << "F";
cout << (isFreezing(c) ? " (freezing)" : "") << endl;
}
int main() {
printReading(20);
printReading(-5);
return 0;
}20C = 68F
-5C = 23F (freezing)Line-by-line explanation
- Lines 4 to 6Returns a double calculated from its parameter.
- Lines 8 to 10A yes/no function returns a bool.
- Lines 12 to 15A void function that uses the other two.
- Lines 18 to 19main stays short and readable.
Value versus reference
#include <iostream>
using namespace std;
void tryToChange(int x) {
x = 99;
}
void reallyChange(int& x) {
x = 99;
}
int main() {
int a = 1, b = 1;
tryToChange(a);
reallyChange(b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}a = 1, b = 99Line-by-line explanation
- Line 4x is a copy, so changing it doesn't affect a.
- Line 8int& makes x another name for b itself.
- Line 16Only b was changed.
Default arguments and overloading
#include <iostream>
#include <string>
using namespace std;
string repeat(string text, int times = 2) {
string result = "";
for (int i = 0; i < times; i++) result += text;
return result;
}
int biggest(int a, int b) { return a > b ? a : b; }
double biggest(double a, double b) { return a > b ? a : b; }
int main() {
cout << repeat("ha") << endl;
cout << repeat("ho", 3) << endl;
cout << biggest(4, 9) << " " << biggest(2.5, 1.5) << endl;
return 0;
}haha
hohoho
9 2.5Line-by-line explanation
- Line 5times defaults to 2 when the caller leaves it out.
- Lines 11 to 12Two functions share the name biggest, with different parameter types.
- Line 17The compiler picks the int version, then the double version.
Common C++ Functions Mistakes
Calling a function before it's declared
int main() {
sayHi();
}
void sayHi() { cout << "Hi"; }void sayHi() { cout << "Hi"; }
int main() {
sayHi();
}The compiler reads top to bottom and reports "'sayHi' was not declared in this scope".
Forgetting & when you want to change a variable
void reset(int score) { score = 0; }void reset(int& score) { score = 0; }Without &, only the copy is reset.
Missing return in a non-void function
int half(int n) {
int h = n / 2;
}int half(int n) {
return n / 2;
}Reaching the end of a non-void function without return gives an unpredictable value. Compile with -Wall to get a warning.
C++ Functions in Real Projects
Functions in large C++ projects
The C++ standard library is a huge set of tested functions: std::sort, std::max, std::find and hundreds more. Game engines expose functions like spawnEnemy(position) and playSound(name, volume = 1.0), and teams split work by agreeing on function prototypes in header files.
C++ Functions FAQ
How do I return more than one value from a function in C++?
Return a struct with named members, which is the clearest option and is shown in the structs lesson. For two quick values, return a std::pair and unpack it with structured bindings: auto [q, r] = divide(7, 2); where divide returns pair<int, int>. Reference parameters such as int& result also work, but they make calls harder to read.
What is the difference between a parameter and an argument?
A parameter is the variable in the function's definition, like n in int square(int n). An argument is the actual value you pass when you call it, like 6 in square(6). When the call runs, the parameter starts out holding a copy of the argument, or refers to it if the parameter is a reference.
When should I pass by const reference instead of by value?
Pass small built-in types such as int, double, char and bool by value; copying them is as cheap as passing a reference. Pass strings, vectors and your own structs and classes by const& when the function only reads them, so nothing is copied. Use a plain & only when the function is meant to change the caller's variable.
Why do I get "call of overloaded function is ambiguous"?
The compiler found two or more overloads that fit the call equally well and can't choose. With biggest(int, int) and biggest(double, double), the call biggest(4, 2.5) mixes an int and a double, and either version would need one conversion. Make the arguments the same type, for example biggest(4.0, 2.5), or add an overload that matches exactly.
Where do default arguments go when I use a prototype?
Put the default value in the prototype only: void greet(string name, string greeting = "Hello");. The later definition repeats the parameters without the = "Hello". Writing the default in both places is an error, because a default argument can only be given once.
C++ Functions Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Complete the function so it returns the larger of two ints.
maxOf(int a, int b) {
a > b ? a : b;
}
What does this print?
int add(int a, int b = 5) { return a + b; }
// in main:
cout << add(1) << " " << add(1, 1);
What does this print?
void bump(int& n) { n++; }
// in main:
int x = 3;
bump(x);
bump(x);
cout << x;
What does const string& name mean for a parameter?
Which declaration lets a function change the caller's variable?
C++ Functions Quiz
5 questions to check what you learned.
What return type does a function that returns nothing use?
- null
- empty
- int
- void
What is a function prototype?
- A declaration of the function's signature, ending in a semicolon
- An unfinished function
- A function with no parameters
- A function inside main
What does
&after a parameter's type do?- Makes it optional
- Makes it constant
- Passes the argument by reference
- Doubles its value
Which pair of functions is a valid overload?
- int f(int a) and int f(double a)
- int f(int a) and double f(int a)
- int f(int a) and int f(int b)
- void f() and int f()
What is a function prototype?
- The first call to a function
- A declaration of the function's name, parameters and return type before its body
- A function with no body ever
- A template