What are Functions in C++

beginner c++17

Functions in every programming language let you abstract away logic in your program for later reuse. Any reasonably sized program will have hundreds to thousands of functions that collectively implement the program.

Functions in C++ accept any number of input parameters and return a single value or object as a result. Functions C++ have names that identify them within your program just like variables. You use a function’s name to call that function, passing any required parameters and receiving the return value. Functions can be of any size, from a single line of code to thousands of lines for single function. As many as it takes to produce the result. Here’s an example of some simple functions:

#include <iostream>
#include <vector>

int add(int a, int b) {
  return a + b;
}

float average(const std::vector<int>& numbers) {
  float sum = 0;
  for (int i : numbers) {
    sum += i;
  }
  return sum / numbers.size();
}

int main() {
  int result = add(40, 2);
  std::cout << result << "\n";

  std::vector numbers{70, 80, 90, 100};
  float avg = average(numbers);
  std::cout << avg << "\n";
}
42
85

Note that main() here is the special function in C++ that is always called when your program starts. Main is the only function in C++ where the return statement value is optional. If left out C++ returns 0 for you from main().

Returning Values

If a function declares a return type it must return a value of that type (except for main as we just explained). Functions are not required to declare a return type though. In C++ we use the keyword void to say a function returns no values. If a function returns void no return statement is necessary.

#include <iostream>

int multiply(int a, int b) {
  return a * b;
}

void print_int(int a) {
  std::cout << a << "\n";
}

int main() {
  print_int(42);

  print_int(multiply(7 * 3));
}
42
21

Returning Multiple Values

Functions in C++ always return one value. However that one value can be a struct or class that itself is composed of multiple values. Returning a struct from a function is a common way to return multiple values in C++.

#include <iostream>

struct Point {
  int x;
  int y;
};

Point add_points(Point a, Point b) {
  return Point{a.x + b.x, a.y + b.y};
}

void print_point(Point p) {
  std::cout << "Point{" << p.x << ", " << p.y << "}\n";
}

int main() {
  Point a{1, 2};
  Point b{3, 4};

  Point c = add_points(a, b);

  print_point(c);
}
Point{4, 6}

For more C++ By Example, click here.