Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Functions

A function is a named block of code that does one job. Functions let you reuse code, give a name to each step of a program and keep each part small enough to understand.

Defining and calling

#include <iostream>

void greet() {
    std::cout << "Hello from a function!\n";
}

int square(int x) {
    return x * x;
}

int main() {
    greet();
    std::cout << square(6) << "\n";
    std::cout << square(3) + square(4) << "\n";
    return 0;
}
Output
Hello from a function!
36
25

The function's first line gives the return type (void for nothing), the name and the parameters. return gives back a value and ends the function.

A function that decides

#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 true;
}

int main() {
    std::cout << "Primes below 30:";
    for (int n = 1; n < 30; n++) {
        if (isPrime(n)) std::cout << " " << n;
    }
    std::cout << "\n";
    return 0;
}
Output
Primes below 30: 2 3 5 7 11 13 17 19 23 29

Declaration before use

The compiler reads from top to bottom, so a function must be declared before it is called. Either define it above main, or write a declaration (prototype) above and the definition below:

#include <iostream>

double average(double a, double b);   // declaration

int main() {
    std::cout << average(81, 90) << "\n";
    return 0;
}

double average(double a, double b) {  // definition
    return (a + b) / 2;
}
Output
85.5

In larger programs, the declarations go into header files (.h or .hpp) and the definitions into .cpp files.

Good functions

  • One job per function, with a name that says it: isPrime, printReport, calculateTax.
  • Short: if a function needs a scroll bar, it probably does several jobs.
  • Inputs as parameters, results as return values, rather than global variables.
  • If a block of code needs a comment saying what it does, it may want to be a function with that name.

Common mistakes

  • **Forgetting return** in a function that promises a value: the result is garbage. With -Wall the compiler warns non-void function does not return a value.
  • Calling a function before it is declared: the compiler stops with use of undeclared identifier. Move the function above, or add a declaration.
  • Expecting a parameter change to reach the caller: parameters are copies unless they are references (see Function Parameters).

Practice exercises

  1. Write int maximum(int a, int b) and use it to find the largest of three numbers.
  2. Write double toFahrenheit(double c) and print a table from 0 to 100 °C.
  3. Write int digitSum(int n) and print the digit sum of 2026.