Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variables declared inside do-while loop in the condition [duplicate]

Tags:

c++

do-while

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.

like image 230
José D. Avatar asked Aug 30 '13 20:08

José D.


People also ask

Can I declare a variable in a Do While loop?

Yes. you can declare a variable inside any loop(includes do while loop.

Can you declare inside a for loop in C?

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.)


2 Answers

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 {}.

like image 61
Carl Norum Avatar answered Oct 19 '22 20:10

Carl Norum


There is a reason why this can't be possible. It is due to the limitation of "statement-scope".

Your variables i and j have been declared with "local scope" -- that is variables inside {} brackets. You actually wanted j to be declared with "statement scope" but this is not possible.

Statement-scope are those variables declared as part of 'for', 'while', 'if' or 'switch' statements. Statement scope does not cover do-while statements, though, which is why you cannot do this.

You have basically exposed a language drawback of using do-while.

It would be better if the language offered:

do {
.
.
.
} while (int j < 100);

but it does not offer this.

like image 43
Faisal Memon Avatar answered Oct 19 '22 19:10

Faisal Memon