Elastic Lamb
Elastic Lamb

Reputation: 353

Variable declaration in C++ within namespaces

In a library I am working with some variables are declared like that:

char &ns::x = y;

However, if I do it that way I get the following error: error: no member named 'x' in namespace 'ns'

If I rewrite it, it works:

namespace ns {
    char &x = y;
}

What exactly is the difference? And why is it working within the library?

Upvotes: 0

Views: 321

Answers (3)

Dharmik Unagar
Dharmik Unagar

Reputation: 58

The Variable declaration using namespace:

#include <iostream> 
using namespace std; 

// Variable created inside namespace 
namespace first 
{ 
  int val = 500; 
} 
// Global variable 
int val = 100; 
int main() 
{ 
// Local variable 
   int val = 200; 
// These variables can be accessed from 
// outside the namespace using the scope 
// operator :: 
   cout << first::val << '\n';  
   return 0; 
} 

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

The first declaration

char &ns::x = y;

assumes that the name x is already declared in the namespace ns. However this assumption is wrong (in the provided code snippet there is no previous declaration of the variable. Possibly the code snippet is not complete.).

The code snippet can works provided that the variable x is already declared (without its definition) in the namespace ns.

For example

#include <iostream>

namespace ns
{
    extern char &x;
}

char y;
char & ns::x = y;

int main() {
    return 0;
}

In this code snippet

namespace ns {
    char &x = y;
}

there is defined a reference that is initialized by the object y.

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545508

If you’re right and the code from the library is exactly as written, then this implies that elsewhere in this library, you’ll find the following declaration:

namespace ns {
    extern char& x;
}

In other words, x must have already been declared (and not defined!) inside ns.

Upvotes: 3

Related Questions