Search code examples
c++functionbuilt-in

"built-in" functions in C++


I'm beginner at C++ so if the answer is obvious it possibly is the one I'm looking for. I was reading the second response in this thread and got confused.

#include <algorithm>
#include <cassert>

int
main()
{
    using std::swap;
    int a(3), b(5);
    swap(a, b);
    assert(a == 5 && b == 3);
}

What I don't get is "This is just a defined function. What I meant was, why it is not directly built-in" but there was no need to include a new library so isn't it built-in? Does the std library automatically get imported (if yes, why doesn't the namespace automatically get set to std)?


Solution

  • "This is just a defined function. What I meant was, why it is not directly built-in" but there was no need to import a new library so isn't it built-in? Does the std library automatically get imported (if yes, why doesn't the namespace automatically get set to std)?

    Well, by defined function it means, most likely that the function is already pre-written, and defined in the library, it isn't directly built-in probably because it was designed that way; only core essentials were included in the language, and everything else is in a library so the programmer can import what they want.

    By built-in, usually it's a keyword, like for or while.

    And no, std isn't automatically imported since it's designed so the programmer can choose what namespaces they want, like custom namespaces or std. An example of this being bad to automatically have std is this:

    Say you automatically defined std, then you wanted to do using namespace foo;, now if foo also had function cout, you would run into a huge problem, like say you wanted to do this;

    // code above
    cout << "Hello, World" << endl;
    // code below
    

    how would the compiler which namespace function to use use? the default or your foo namespace cout? In order to prevent this, there is no default namespace set, leaving it up to the programmer.

    Hope that helps!