onur cevik
onur cevik

Reputation: 107

C++ Why this doesn't cause redecleration error?

#include <iostream>
using namespace std;
namespace extra
{ int i; }//Declared an integer i here
    void i()
    {
       using namespace extra;
       int i; //We called namespace extra at above then we declared another i
       i=9;
       cout<<i;
    }
    int main()
    {

        enum letter{i,j};
        class i{letter j;};
        ::i();

        return 0;
    }

As I explained with the comments above we first declare an integer i at namespace extra then after calling it we declare another integer i then give it a value 9. My question is why this doesnt cause a redecleration error? Also at code line

i=9;

which i value gets the value 9 ? The one inside the namespace or the one inside the void i() function ?

NOTE: Please excuse my poor English.

Upvotes: 0

Views: 59

Answers (1)

Rakete1111
Rakete1111

Reputation: 49018

It's the local one. As a rule of thumb, it is always the "closest" definition that is used.

struct A {};
int A = 0;
A b; // not ok, because A is the variable.

There is no error because there is no name i that denotes a variable in the global scope, or in the function.

A using directive just tells the compiler that if it can't find an appropriate name in the current context, it should also look in that namespace as well. In your case, the compiler didn't need to go into extra to look for a i, because it already found one in the function i.

Upvotes: 1

Related Questions