C++ reason for compilation error

Apr 13, 2019 at 5:13pm
Can someone explain why does the code below give a compilation error? Revising for a test. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
What is the output of the following code?
#include <iostream>
namespace first {
   int var = 5;
}
namespace {
   double var = 3.1416;
}
int main(void) {
   using namespace first;
   std::cout << var;
   return 0;
}
Compilation error 
Apr 13, 2019 at 5:16pm
Error messages can often give you a hint as to what the problem is.
Apr 13, 2019 at 5:18pm
The unnamed namespace has global scope, so, having also put the 'first' namespace in scope, you will have two conflicting variables var.

Try naming the second namespace something - then there will be no ambiguity and the output will be 5.
Apr 13, 2019 at 5:34pm
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
namespace first {
   int var = 5;
}
namespace {
   double var = 3.1416;
}
int main(void) {
   using namespace first;
   std::cout << ::var << " "<< first::var;
   return 0;
}
Topic archived. No new replies allowed.