← C++ tutorial

C++

Functions

A function declares its return type, name, and parameter types up front: int add(int a, int b) { ... }.

Example: a function used before main()

#include <iostream>
using namespace std;

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

int main() {
    cout << "Square of 6 is " << square(6) << endl;
    return 0;
}
Square of 6 is 36

Unlike some languages, C++ generally requires a function to be declared (or at least its signature known) before the point where it's called, here, square is defined entirely above main, so by the time main calls it, the compiler already knows exactly what square looks like. Use void as the return type for a function that doesn't return a value at all.

Example
#include <iostream>
using namespace std;

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

int main() {
    cout << "Square of 6 is " << square(6) << endl;
    return 0;
}
Output
Square of 6 is 36
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account