Maestairs
Maestairs

Reputation: 95

VC++ Compiler options

I have a VC++ 6.0 project which I am now compiling using VS2008 . I have this piece of code that used to compile under VC++ 6 but throws an error under VS2008 :

int CIDStorage::Length()

{

CIDStorage* m_ptr = this;

    for(int i = 0;m_ptr->m_ptrNext != NULL;i++)
        m_ptr = m_ptr->m_ptrNext;

    if(i == 0)
        if(m_ID.IsEmpty())
            return 0;

    return i+1;
}

the error is 'i' : undeclared identifier

No probs with that I can see how that came about . So ... Do I change the source code . Or is there a compiler setting I could set that cures this ?

Upvotes: 1

Views: 247

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490008

VC++ 6 (normally1) follows a pre-standard rule where a variable defined in a for loop remains defined for the rest of the scope in which that for loop resides. VC++ 2008 follows the standard rule where the for loop defines a new scope, and the variable is defined only within that scope.

The cure is pretty simple -- define the variable outside the loop:

int CIDStorage::Length()
{
    CIDStorage* m_ptr = this;
    int i;

    for(i = 0; m_ptr->m_ptrNext != NULL; i++)
        m_ptr = m_ptr->m_ptrNext;

    if(i == 0)
        if(m_ID.IsEmpty())
            return 0;

    return i+1;
}

1 The compiler in VC++ is actually capable of following the correct rules for scoping of variables defined in a for loop. Unfortunately, to follow the rule, you have to use the /Za flag, which tries to enforce all the rules it knows as strictly as possible. That turns out to be completely unusable because with that turned on, it rejects (virtually?) all of its own headers as containing errors!

Upvotes: 2

Related Questions