tags:

views:

23

answers:

2

Hi,

I am porting a C++ project to VS2008. Piece of the code has a variable declared in the for loop statement as below:

for(bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it) {

}

"it" is later used as an index in another for loop statement as below: for(it = bitmaps.begin(); it != bitmaps.end(); ++it) {

}

It generates error c2065 in debug build wit hthe below project settings where as release build was successful.

I have set the C\C++ > Language> For Conformance In For loop Scope to No (/Zc:forscope- ) and built the project with release configuration mode. Code was built succesfully.

The same code with the same settings fail to build in debug mode. Can anyone help me to resolve the issue.

Any help is appreciated.

Thanks, Lakshmi

+1  A: 

The it variable is declared within the for loop initializer list, which means its scope ends along with the for loop scope. Setting /Zc:forscope- option enables the MS specific extension which keeps the it declaration alive until the end of the enclosing scope in which your for loop is defined (for example, whatever function body your code snippet exists in). IMHO, you shouldn't be using the /Zc:forscope- flag since it compiles non-standard code without errors. To fix your problem you can do one of two things:

bmpMapType::const_iterator it;
//first loop
for( it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
...
//second loop
for( it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }

OR

//first loop
for( bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
...
//second loop
for( bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it ) { ... }
Praetorian
Thankyou. That works fine. I have a question why it works in release mode without declaring it again as mentioned
Lakshmi
Make sure the `/Zc:forscope` flag has the same setting in both Debug and Release modes, as far as I know it should either build or fail in both build configurations if that flag is set consistently.
Praetorian
A: 

A simple fix may be just to modify the second loop to match the first - declaring its own copy of it as per

for(bmpMapType::const_iterator it = bitmaps.begin(); it != bitmaps.end(); ++it) {

}

unless there is some place in between the loops where the first it is used. If usage of each is entirely local to their respective loops then just do this and get on with your port.

Steve Townsend