C++

What is Namespace in C++

Consider the Following Example:

Problem 1:

Suppose we take two variable x but different type one is int type and another is double type in same scope.

#include <iostream>
int main()
{
    int x;
    x=6;
    double x;
    x = 1.5;
    return 0;
}

Following error comes when we run same variable name but different types.

main.cpp: In function ‘int main()’: main.cpp:8:12: 
error: conflicting declaration ‘double x’ double x; ^ 
main.cpp:6:9: note: previous declaration as ‘int x’ int x; ^ 

Problem with this code is each variable have unqiue entity in there scope.

Problem 2:

Suppose we use two mobile app on my phone

1. Before Update: both the app have a different – different variable names and function name, so OS will be no conflict in using there function and variable.

2. After Update : One function name same as another App function name ,when OS call this function then OS will confuse which App function will be call.

3. To Resolve these problem we simple add App name before function ,This way OS will be understand ,which App function will be call.

Solution

Example 1:

#include <iostream>
using namespace std;
  //declare namespace 
    namespace Fun1
    {
    int x=5; 
   }
    namespace Fun2
    {
        int x=6;
    }
int main()
{    
// Here we given scope to the x,By given scope compiler not confused and simply detect x belong to which namespace 
  cout<<Fun1::x;
    return 0;
}
5
#include <iostream>
using namespace std;
  
    namespace Fun1
    {
    int fun()
    {int x=5; 
        
        return x;
    }
   
    }
    namespace Fun2
    {
    int fun(){ int x=6;
    
    return x;
    }
    }
int main()
{    
  cout << Fun1::fun();
    return 0;
}
5
  1. Namespace is a keyword in Cpp not in C language.
  2. It will be provided scope to the identifier like variable ,functions inside it.
  3. Baisc Syntax of namespace:
namespace identifier { entities }

What is namespace std ?

  1. We use “using namespace std” in C++ program before the main class.
  2. The reason of using this is all the standard libraries of c++ define in the std namespace.
  3. For Example :We also use std::cin>> instead of cin>> ,std::cout<< instead of ” cout<< ”

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading