CodeMIRAI
0 XP

Functions

2 min read 4 runnable examples Quiz included
C++
#include <iostream>
using namespace std;

double circleArea(double r) {
    return 3.14159 * r * r;
}

void greet(int times) {
    for (int i = 0; i < times; i++) cout << "Hello! ";
    cout << endl;
}

int main() {
    cout << circleArea(2) << endl;
    greet(3);
    return 0;
}

A function definition has a return type (double, or void for nothing), a name, and parameters with their types.

Default arguments

Parameters can have defaults, used when the caller leaves them out:

C++
#include <iostream>
using namespace std;

int power(int base, int exponent = 2) {
    int result = 1;
    for (int i = 0; i < exponent; i++) result *= base;
    return result;
}

int main() {
    cout << power(5) << endl;      // exponent defaults to 2
    cout << power(2, 10) << endl;
    return 0;
}

Declare before use

As in C, a function must be declared before it's called. A declaration (prototype) at the top lets you put definitions anywhere:

C++
#include <iostream>
using namespace std;

bool isPrime(int n);   // declaration

int main() {
    for (int n = 2; n <= 30; n++) {
        if (isPrime(n)) cout << n << " ";
    }
    cout << endl;
    return 0;
}

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

Recursion

C++
#include <iostream>
using namespace std;

int fib(int n) {
    if (n < 2) return n;
    return fib(n - 1) + fib(n - 2);
}

int main() {
    for (int i = 0; i < 12; i++) cout << fib(i) << " ";
    cout << endl;
    return 0;
}

Passing by value

By default, C++ passes a copy of each argument. C++ also offers references (int &x) that let a function change the caller's variable directly; those are covered in the references lesson, which runs on the full compiler.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.