Use the variables declared in the do-while loop in the condition


This question already has an answer here:

  • Why is while's condition outside the do while scope 1 answer

I was writing something like this code:

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

} while (j < 100);


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.

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.