Functions
A function has a return type, a name and parameters. Parameters are copied by default. Add & to pass by reference so the function can change the caller's variable. Default arguments and overloading are allowed.
Example
#include <iostream>
using namespace std;
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
void greet(string name = "friend") { cout << "Hello, " << name << endl; }
void addOne(int& n) { n++; }
int main() {
cout << add(2, 3) << " " << add(1.5, 2.5) << endl;
greet();
greet("Ada");
int x = 5;
addOne(x);
cout << x << endl;
}Result
5 4 Hello, friend Hello, Ada 6
Exercise
Pass by reference.
void addOne(int n)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.