Use variables declared inside do-while loop in the condition

José D. picture José D. · Aug 30, 2013 · Viewed 11.1k times · Source

I was writing something like this code:

do {
    int i = 0;
    int j = i * 2;
    cout<<j;

    i++;
} while (j < 100);

(http://codepad.org/n5ym7J5w)

and I was surprised when my compiler told me that I cannot use the variable 'j' because it is not declared outside the do-while loop.

I am just curious about if there is any technical reason why this cant be possible.

Answer

Carl Norum picture Carl Norum · Aug 30, 2013

The scope of j is just within the {} braces. You can't use it in the loop condition, which is outside that scope.

From a C++ draft standard I have handy:

A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region.

A "block" is also known as a "compound statement", and is a set of statements enclosed in braces {}.