C++ programming 2 min read

Functions

A function packages code under a name, takes parameters and returns a value. Small, well-named functions keep firmware readable, and passing larger data by reference avoids copying it.

int add(int a, int b) { return a + b; }: int is the return type, add is the name, (int a, int b) are the parameters and the braces hold the body. The call int s = add(2, 3); passes the arguments 2 and 3, and s becomes 5.
The parts of a function, and a call to it.

Defining and calling

add.cppC++
#include <iostream>int add(int a, int b) {    return a + b;}int main() {    int s = add(2, 3);    std::cout << "s = " << s << '\n';}
Output
s = 5

By value or by reference

Parameters are copies by default, so a function can’t change the caller’s variable. A reference parameter (int&) refers to the caller’s variable itself. A const reference avoids the copy without allowing changes.

reference.cppC++
#include <iostream>int doubled(int x) {          // works on a copy    x *= 2;    return x;}void double_in_place(int& x) { // changes the caller's variable    x *= 2;}int main() {    int a = 21;    std::cout << doubled(a) << ' ' << a << '\n';    double_in_place(a);    std::cout << a << '\n';}
Output
42 21
42