Function (C++)

A function is a named, reusable block of code. In C++ you declare its return type, name, and parameters, then call it to run its body and optionally get a value back.

C++

Every C++ program starts in a special function called main(). A function's signature includes its return type (use void if it returns nothing) and the types of its parameters.

Functions can be overloaded — several functions can share a name as long as their parameter lists differ. Pass large objects by reference to avoid copying them.

Syntax

returnType name(parameters) { /* body */ return value; }

Examples

C++

#include <iostream>

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

int main() {
    std::cout << square(4) << std::endl;
    return 0;
}

Output:

16

Learn it in a lesson

See also

Back to the Dictionary