0

I have this old piece of code (modified to be compilable), which I would assume gives a warning for variable redefinition on pos, but it doesn't. Could anyone tell me why it doesn't ?

Kind Regards

https://www.onlinegdb.com/ByUR079yS

#include <iostream>
#include <vector>

using namespace std;

struct foo
{
    std::vector<int*> bar;
};

int main()
{
    std::vector<foo*> m_ListCilinders;
    for (std::vector<foo*>::iterator pos = m_ListCilinders.begin(); pos != m_ListCilinders.end(); pos++)
    {
        foo* pCilinder = *pos;

        for (std::vector<int*>::const_iterator pos = pCilinder->bar.begin(); pos != pCilinder->bar.end(); pos++)
        {
            int* pLevering = *pos;
        }
    }

    return 0;
}
Minion91
  • 1,911
  • 12
  • 19
  • 3
    There's no warning required, because the code is perfectly legal. Two distinct variables, which happen to have the same name, are defined in different scopes. Some compilers can be configured, optionally, to warn about such things. – Peter Jun 21 '19 at 10:26
  • Thanks. But the second scope is inside the first scope. How does the compiler know which one to use in the second case ? – Minion91 Jun 21 '19 at 11:29
  • 1
    @minion91 it uses the one in the newest, or most recent scope by default. I highly recommend not doing that unless you know what you're doing, even then only if you have to. Otherwise that's a recipe for bugs. Not that you were planning on doing that. I'm just making it clear that's not recommended that you do that in general. –  Jun 21 '19 at 12:32
  • Yea, this isn't my code, and I would never do this, but I was surprised this actually gave no warnings. – Minion91 Jun 21 '19 at 12:43

0 Answers0