Default Values, Overloading and Scope

Default parameter values

You can give a parameter a default value. If the caller leaves it out, the default is used:

#include <iostream>
#include <string>
using namespace std;

void order(string drink, int cups = 1) {
    cout << cups << " x " << drink << "\n";
}

int main() {
    order("tea", 3);
    order("coffee");      // cups is 1
    return 0;
}

Output

3 x tea
1 x coffee

Tip: Parameters with defaults must come last in the list.

Overloading: same name, different parameters

C++ lets several functions share a name as long as their parameters are different. C++ picks the right one by looking at the arguments:

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

int add(int a, int b, int c) {
    return a + b + c;
}

int main() {
    cout << add(2, 3) << "\n";
    cout << add(2.5, 1.25) << "\n";
    cout << add(1, 2, 3) << "\n";
    return 0;
}

Output

5
3.75
6

Scope: where a variable lives

A variable created inside a function (or inside any { }) is local: it only exists there. Two functions can each have their own x without any problem:

#include <iostream>
using namespace std;

void test() {
    int x = 100;          // this x belongs to test()
    cout << "In test: " << x << "\n";
}

int main() {
    int x = 5;            // a different x, belonging to main()
    test();
    cout << "In main: " << x << "\n";
    return 0;
}

Output

In test: 100
In main: 5

A variable created outside all functions is global and can be used anywhere. It is handy for constants, but avoid global variables that change – they make bugs hard to find.

HOME LABS COMMUNITY DASHBOARD