01 / 21
f(x)

Defining & Calling
Functions in C++

Learn how to define reusable blocks of code, pass parameters, and use return types to build modular programs.

C++ Functions

What Is a Function?

A function is a named, self-contained block of code that performs a specific task. Instead of writing the same logic repeatedly, you write it once inside a function and call it whenever needed.

Reusability
Write once, call from many places in your program.
Modularity
Break complex problems into small, manageable pieces.
Readability
Give descriptive names so others understand your logic instantly.

Anatomy of a Function

int add ( int a , int b ) { return a + b ; } Return Type Function Name Parameters Function Body Every part has a specific role in defining what the function does.

Why Functions Matter

Without functions, programs become long, repetitive, and hard to debug. Functions let you isolate logic, test pieces independently, and collaborate with other programmers.

Without Functions // compute area double a1 =
\(3.14 \cdot r_1 \cdot r_1;\)
// compute area again double a2 =
\(3.14 \cdot r_2 \cdot r_2;\)
// and again... double a3 =
\(3.14 \cdot r_3 \cdot r_3;\)
Repetitive and error-prone With Functions double area(double r){ return
\(\color{#f78c6c}{3.14} \cdot r \cdot r;\)
} a1 = area(r1); a2 = area(r2); a3 = area(r3); Clean, reusable, one fix

The Function Syntax Rule

C++ Syntax
returnType functionName(paramType param1, paramType param2) {
    // function body: statements that do the work
    return value;   // send a result back to the caller
}
1
Return type: the data type of the value the function sends back (e.g. int, double, void).
2
Function name: a descriptive identifier following C++ naming rules.
3
Parameters: input variables declared inside parentheses, separated by commas.
4
Body: the curly-braced block containing statements and (usually) a return.

Understanding Return Types

The return type tells the compiler what kind of data the function produces. If a function doesn't produce a value, use void.

int
Returns a whole number, like a count or index.
double
Returns a decimal number, like a measurement or ratio.
bool
Returns true or false for yes/no decisions.
void
Returns nothing: just performs an action (print, modify, etc.).

Parameters vs Arguments

int multiply ( int x , int y ) { ... } PARAMETERS call site int result = multiply ( 5 , 3 ARGUMENTS Parameters are the placeholder variables in the definition. Arguments are the actual values you pass when calling.

How a Function Call Works

1. Caller invokes add(5, 3) 2. Arguments copied to params a = 5, b = 3 3. Body executes return a + b; // = 8 4. Value returned to caller int result = 8; 5. Execution continues after the call site

void vs Non-void Functions

void Function Non-void Function
Purpose Performs an action (side effect) Computes and returns a value
Return statement Optional (or return;) Required with a value
Can assign to variable? No Yes
Example void greet() int add(int a, int b)

How to Write a Function

1
Identify the task: What specific job should this function do? Give it a clear, descriptive name.
2
Determine inputs: What data does it need? List each parameter with its type.
3
Determine output: Does it return a value? If yes, choose the return type. If not, use void.
4
Write the body: Implement the logic using the parameters. End with a return if non-void.
5
Call the function: Use its name with arguments in parentheses at the call site.

Example 1: Square a Number

C++
int square(int n) {
    return n * n;
}

int main() {
    int result = square(7);
    cout << result;   // Output: 49
    return 0;
}

Example 2: Max of Two Values

C++
int maxVal(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}

int main() {
    cout << maxVal(12, 8);   // Output: 12
    cout << maxVal(3, 15);    // Output: 15
    return 0;
}

Example 3: A void Function

C++
void printLine(string msg, int times) {
    for (int i = 0; i < times; i++) {
        cout << msg << endl;
    }
}

int main() {
    printLine("Hello!", 3);
    // Prints "Hello!" three times
    return 0;
}

Declaration vs Definition

C++
// Declaration (prototype) - tells compiler the function exists
int add(int a, int b);

int main() {
    cout << add(2, 3);   // Works because of the prototype above
    return 0;
}

// Definition - provides the actual body
int add(int a, int b) {
    return a + b;
}

Common Mistakes

✕ Missing Return
Declaring int foo() but forgetting the return statement. The compiler may warn, and the result is undefined.
✕ Type Mismatch
Returning a string from a function declared as int. The return type and actual value must match.
✕ Wrong Argument Count
Calling add(5) when it expects two parameters. Every parameter needs a matching argument.
✕ Assigning void
Writing int x = printMsg(); when printMsg is void. You can't store "nothing".

Summary Cheat Sheet

Concept Meaning Example
Return type Data type of the output int, void
Parameter Placeholder in definition int x
Argument Actual value at call site 5
Prototype Forward declaration int add(int, int);
Function call Execute the function add(2, 3)

Question 1 of 5

What is the return type of the following function?

void displayScore(int score) { ... }

Question 2 of 5

Given the function:

double half(double x) { return x / 2.0; }

What does half(10.0) return?

Question 3 of 5

Which line is a valid function prototype (declaration)?

Question 4 of 5

What is wrong with this code?

int getAge() { cout << 25; }

Question 5 of 5

In the call greet("Alice", 3), what are "Alice" and 3 called?