C/C++ Arena

Step 5 of 7

Namespaces and using

Large programs combine code from many libraries, and two libraries might both define a function called load or a type called Config. C++ avoids these clashes with namespaces: named scopes that group related names.

#include <iostream>
#include <string>

namespace audio {
    int volume = 7;
    std::string name() { return "audio"; }
}

namespace video {
    int volume = 3;
    std::string name() { return "video"; }
}

using std::cout;

int main() {
    cout << audio::name() << " " << audio::volume << "\n";
    cout << video::name() << " " << video::volume << "\n";
}
audio 7
video 3

Shortening names

Most professional code simply writes std:: everywhere; it quickly becomes invisible.

Your turn: fill in the scope operators and the using-declaration.

Previous: bool, auto and range-for Next: Whole lines with getline