What we use ‘using namespace std’ mean in C++?

in c++ why this namespace is used?

Better Asked on June 7, 2020 in Programming.
Add Comment
  • 1 Answer(s)

    First let’s understand what a namespace is:

    Consider this ,

    There are two students in one classroom having same name for example Vishal. now if we need to differentiate each of them , we would have to use some info along their name like their area of living , physical characteristics etc.

    same goes with namespaces in C++ , you might have a variable named for example value in your C++ program , and there maybe a library which contains a variable named value in it. now there is no way for the compiler to know which version of variable value is being called in the code.

    a namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions , variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined.

    Now let’s see what namespace std is :

    std is an abbreviation of standard. std is the standard namespace. cout, cin and a lot of other things are defined in it. you can also call these functions using std::cout , std::cin etc.

    What using does :

    The keyword using technically means, use this whenever you can. This refers, in this case, to the std namespace. So whenever the computer comes across cout, cin, endl or anything of that matter, it will read it as std::cout, std::cin or std::endl.

    When you don’t use the std namespace, the computer will try to call cout or cin as if it weren’t defined in a namespace (as most functions in your codes). Since it doesn’t exist there, the computer tries to call something that doesn’t exist! Hence, an error occurs. so essentially , without using namespace std; when you write for example cout << value; you’d have to put std::cout << value;

    Here’s a small example for you:

    #include <iostream>

    int main()

    {

    std::cout << “Hello World”;

    return 0;

    }

     

     

    #include <iostream>

     

    using namespace std; //now you don’t have to write ‘std::’ anymore.

     

    int main()

    {

    cout << “Hello World”;

    return 0;

    }

    Better Answered on June 7, 2020.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.