Functions
A function packages up a piece of logic so you can reuse it by name, instead of retyping the same code everywhere.
#include <iostream>
#include <string>
int add(int a, int b) {
return a + b;
}
void greet(const std::string& name) {
std::cout << "Hello, " << name << "!" << std::endl;
}
int main() {
std::cout << "add(2, 3) = " << add(2, 3) << std::endl;
greet("Kodstigen");
return 0;
}
Key ideas
- A function's declared return type (
int,void, ...) must match what it actually returns,voidmeans "returns nothing". - In
add(int a, int b),aandbare parameters, placeholders for whatever values get passed in when the function is called (the actual values, like2and3, are called arguments). - Passing a parameter as
const std::string&passes it by reference instead of copying it, faster for large objects like strings, andconstpromises the function won't modify it. - Functions must generally be declared (or defined) before they're used, that's why
addandgreetappear abovemain.