C++: Variables with same name (order of operations) (Scope)

73 views Asked by At

I'm fixing visual studio warning 4456 (local declaration of 'pLine' hides previous declaration), when I came across code that looks like this...

CObject* pLine;
for(i)
{
  CObject* pLine = pLine = GetObjectPtr(i);
  list.Add(pLine)
}
pLine = GetObjectPtr(0);
DoStuff(pLine);

for clarity I will tag them with 1 & 2

CObject* pLine1 = NULL;
for(i)
{
  CObject* pLine2 = pLine? = GetObjectPtr(i);
  list.Add(pLine2)
}
pLine1 = GetObjectPtr(0);
DoStuff(pLine1);

I don't need to know how to fix this code; since the next usage of pLine after this loop is a set, it is safe to rename pLine2 or remove the extra declaration.

What I want to know is,,, On this line of code

  CObject* pLine = pLine = GetObjectPtr(i);

Which pLine is the second pLine? Does pLine2 get declared then used immediately? Or is the Operator=() ran with pLine1?

1

There are 1 answers

0
Jarod42 On BEST ANSWER

In

CObject* pLine = pLine = /*...*/;

(New) variable pLine begins at the =, and begins to hide the one from outer scope.

It might be useful in some rare cases with self reference, (but as object is not yet initialized, only reference on it is usable).

void* p = &p;
SomeNode node(node, weight); // And use only &node in constructor.

Code to check that behaviour can be

int i;
void* p = &i;
std::cout << &p << std::endl; // value #1
std::cout << p << std::endl;  // value #2
std::cout << &i << std::endl; // value #2
{
    void* p = &p;
    std::cout << &p << std::endl; // value #3
    std::cout << p << std::endl;  // value #3
}

Demo