З нашими поточними знаннями оновлювати змінну за допомогою функції трохи громіздко. Кожен аргумент функції обробляється як копія і не змінює початкового значення. Залежно від розміру нашого типу це може мати серйозні наслідки для продуктивності нашого коду.
int adjust_salary(int base, int kids) {
return base + kids * 500;
}
int now_a_mother_of_twins{2500};
adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is still 2500
now_a_mother_of_twins = adjust_salary(now_a_mother_of_twins, 2);
// now_a_mother_of_twins is now 3500
References можна розглядати як псевдоніми: зміни в них впливають на початкову змінну.
References використовують амперсанд (&) в оголошенні типу.
int balance{1000};
int& budget{balance};
int pro_computer_wheels{699};
budget -= pro_computer_wheels;
// budget is now 301;
// balance is also 301;
Перепривʼязка (зміна привʼязки reference) неможлива.
Не можна мати неініціалізований reference.
References потрібно ініціалізувати наявною змінною.
int main_acc{1'000'000};
int side_acc{-20};
int& savings{main_acc};
// => main_acc and savings are 1'000'000
// try to reseat savings to use main account
savings = side_acc;
// savings and main_acc are now -20
// as this uses the **value** of side_acc
savings += 20;
// savings and main_acc are now 0, side_acc is stil -20
int& future_budget;
// => compiler error, reference must be bound!
voidЗавдяки силі references нам може взагалі не знадобитися повертати значення з функції.
void у цьому випадку використовується як тип повернення.
void increase_power(int& level) {
level += 500;
}
int goku{8700};
increase_power(goku);
// goku's power level?
// It's over 9000!