All lessons
LESSON 25/53Bigger Programs
More About Functions
GOALLet a function change the original variable, take default values, and share a name.

By default a function receives a copy of its argument, so the original never changes. Adding & passes the original itself instead.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
void addTax(double& price) { // & = эх хувьсагчийг өөрчилнө / & changes the original
price = price * 1.1;
}
int power(int base, int exp = 2) { // exp өгөхгүй бол 2 / exp is 2 if you omit it
int result = 1;
for (int i = 0; i < exp; i++) result *= base;
return result;
}
int main() {
double p = 100;
addTax(p);
cout << p << endl; // 110
cout << power(5) << endl; // 25
cout << power(2, 10) << endl; // 1024
return 0;
}> what you see
110 25 1024
//LINE BY LINE
Watch it run
Inside main there is one box: double p = 100.
A copy, or the original?
| You write | The function gets | Original changes? |
|---|---|---|
void f(int x) | хуулбар / a copy | Үгүй / No |
void f(int& x) | эх хувьсагч / the original | Тийм / Yes |
void f(const int& x) | эх хувьсагч / the original | Үгүй — хамгаалагдсан / No — protected |
const & is ideal for large data (strings, vectors): no copying cost, but still safe from accidental changes.
Functions that share a name
Several functions may share a name as long as their parameters differ. The compiler picks the right one from your arguments.
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
cout << add(2, 3) << endl; // 5 — эхнийхийг дуудна
cout << add(2.5, 3.5) << endl; // 6 — хоёрдахийг дууднаLocal variables
A variable declared inside a function is visible only there. Two functions may use the same name and still be completely separate.
void a() { int count = 1; }
void b() { int count = 99; } // огт өөр хувьсагч
int main() {
// cout << count; ✗ энд count гэж байхгүй
}