Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Recursion

Recursion means a function calls itself, directly or through other functions. For the computation to terminate, it needs a reachable base case and recursive steps that make progress toward that case.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

ReturnType function(Parameters) {
    if (base_condition) return base_value;
    return combine(function(smaller_arguments));
}

Recursion (recursion) is a technique in which a function calls itself directly or indirectly through other functions. It needs no special keyword: it uses ordinary function-call syntax. C++ permits recursive calls, but main must not be called recursively.

A typical algorithm has a base case that returns a result without another call, and a recursive step that reduces the problem. For inputs that should terminate, every chain of calls must reach a base case. Merely having a stopping condition is insufficient if the arguments never satisfy it.

In the example, sum_to(5) computes the sum from 1 through 5. Calls decrease n until it reaches 0; successive returns then add the pending values, producing 15. Each invocation has its own parameter n; this is not one shared variable. For n <= 0, the function returns 0.

Do not treat the example as a solution for arbitrarily large inputs: deep recursion can exhaust execution resources, and a sum outside the range of int causes undefined behavior. For large inputs, consider a loop and range checks. The supplied source is an evolving standard draft, not a frozen C++23 publication; the example uses C++23-compatible syntax.

Examples

#include <iostream>

int sum_to(int n) {
    if (n <= 0) {
        return 0;
    }
    return n + sum_to(n - 1);
}

int main() {
    std::cout << sum_to(5) << '\n';
}

Result

15

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources