Functions in C++

Functions are central in C++. We’ll learn about functions with a few different examples.

#include <iostream>

// Here's a function that takes two ints and returns
// their sum as an int.
int plus(int a, int b) {
    // C++ will automatically return the value of the last
    // expression in a function, but it's good practice to
    // use an explicit return statement.
    return a + b;
}

// In C++, you need to declare the type for each parameter,
// even if they are of the same type.
int plusPlus(int a, int b, int c) {
    return a + b + c;
}

int main() {
    // Call a function just as you'd expect, with
    // name(args).
    int res = plus(1, 2);
    std::cout << "1+2 = " << res << std::endl;

    res = plusPlus(1, 2, 3);
    std::cout << "1+2+3 = " << res << std::endl;

    return 0;
}

To compile and run this C++ program:

$ g++ functions.cpp -o functions
$ ./functions
1+2 = 3
1+2+3 = 6

There are several other features to C++ functions. One is function overloading, which allows multiple functions with the same name but different parameter lists. Another is default arguments, which allow you to specify default values for function parameters.


C++ functions are similar to those in other languages, but with some key differences:

  1. Function declarations (prototypes) are often used in header files, with the implementation in separate source files.
  2. C++ supports function overloading, allowing multiple functions with the same name but different parameter lists.
  3. Default arguments can be specified for function parameters.
  4. C++ supports inline functions for performance optimization.
  5. Function templates allow for generic programming.

These features make C++ functions powerful and flexible, allowing for efficient and reusable code.