blog.dopana

Back

Fourth post in the basic C++ series. Functions let you name a block of code, give it inputs, and call it from anywhere — the core tool for structuring any program.

Why functions?#

Functions make code reusable, testable, and readable. Instead of copying the same logic, you write it once and call it many times.

A first function#

#include <iostream>

int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(3, 4);
    std::cout << result << '\n';  // prints 7
}
cpp

add takes two int parameters and returns an int. The values 3 and 4 are arguments.

Return type and void#

If a function produces no value, its return type is void:

void greet(std::string name) {
    std::cout << "Hello, " << name << "!\n";
}
cpp

Forward declarations#

To call a function before its definition — for example, when splitting code across files — declare it first:

int multiply(int x, int y);   // declaration

int main() {
    std::cout << multiply(6, 7) << '\n';
}

int multiply(int x, int y) {  // definition
    return x * y;
}
cpp

The declaration must match the definition exactly.

Parameters by value#

By default, C++ copies arguments into parameters. Changes inside the function do not affect the caller:

void increment(int x) {
    ++x;
}

int main() {
    int a = 5;
    increment(a);
    std::cout << a << '\n';  // still 5
}
cpp

To modify the caller’s variable, pass a reference — covered in the next post.

Default arguments#

Parameters can have defaults:

void print(std::string msg, int times = 1) {
    for (int i = 0; i < times; ++i) {
        std::cout << msg << '\n';
    }
}

print("hi");        // prints once
print("hi", 3);     // prints three times
cpp

Overloading#

Two functions can share a name if their parameter lists differ:

int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
cpp

The compiler picks the right one from the argument types.

Conclusion#

Functions are the building blocks of C++ programs: declare, define, call, and reuse. Next in this series: pointers and references.

References#