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.
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