Skip to content

Functions in C++

Programming C++ Difficulty 1/5

Beginning of the lesson

Functions in C++

Build your own reusable blocks of code

Big Idea: A function is a named block of code that does one job. You write it once, give it a name, and then call it as many times as you like. Functions keep your programs short, tidy, and easy to fix.
By the end you will be able to:
  • declare and define a function,
  • pass parameters by value and by reference,
  • return a value (or return nothing with void),
  • write overloaded functions that share a name.

1. What is a function?

Think of a function like a kitchen appliance. A blender has a name ("blender"), you put things in (fruit), it does its job, and something comes out (a smoothie). You do not rebuild the blender every time — you just use it again.

A function is the same: you give it a name, it can take some inputs (called parameters), it runs its steps, and it can hand back a result (the return value).

arguments in 3, 4 add(a, b) runs its steps value out 7
A function takes arguments, runs its body, and returns a value — like a machine.

2. Declare vs. define

There are two related ideas:

  • A declaration (also called a prototype) tells the compiler the function's name, what it returns, and what parameters it takes. It ends with a semicolon and has no body.
  • A definition is the real thing: the same header plus the body in { } that does the work.
#include <iostream>
using namespace std;

// Declaration (prototype): promises the function exists.
int add(int a, int b);

int main() {
    cout << add(3, 4) << endl;   // we can call add here
    return 0;
}

// Definition: the real body that does the work.
int add(int a, int b) {
    return a + b;
}

Expected output:

7
The declaration lets main call add even though the full definition appears lower in the file.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers