Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Is This Loop Variable Accessible Outside Loop Scope?

While browsing some C++ code, I came across the following lines :

for (int i = 0; i < count; i++) {
        if (&array[i].GetData() == el)
            break;
}
if (i < count) {
   // .. Do something
}

I am surpised to see that the loop-counter variable i is accessible outside the loop!

Just to ensure that the i outside the loop was same as the one inside the loop, I changed the loop variable name to i1.

for (int i1 = 0; i1 < count; i1++) {
        if (&array[i1].GetData() == el)
            break;
}
if (i < count) {    // COMPILATION ERROR: Identifier i is undefined
   // .. Do something
}

This resulted in a compilation error for the line if(i < count) :

identifier 'i' is undefined.

What is going on? This is too basic to be a compiler bug. If there was another i in a parent scope, there would have been no compilation error. Am I missing something? I am using Visual Studio 2015.

like image 796
johngreen Avatar asked Apr 11 '18 08:04

johngreen


Video Answer


1 Answers

Visual Studio in the past had the feature that extended the lifetime & accessability of variables declared in the for(...) construct (a holdover from plain C behaviour, before the C++98 standard came into being). This behaviour was enabled by default in the older projects.

Microsoft realized that this (for C++) non-standard conforming behaviour might be undesirable and provided the /Zc:forScope compiler option to control this behaviour (and more recently enabled this switch by default, restoring standard C++ conformity).

Check if the /Zc:forScope is set in your project settings under the C++ -> Language rider. If not, set it.

Note: You also have the option to set /Zc:forScope- there to explicitly enable the non-standard behaviour, in case you have legacy code that relies on it.

like image 137
CharonX Avatar answered Sep 21 '22 10:09

CharonX