Scope of variables declared inside do-while
What you'll learn: Why variables created inside a do-while loop are invisible to the loop's own exit condition.
The "Room" Analogy
Think of a pair of curly braces { } in C as a private room. Anything you create inside that room—like a variable—stays in that room. When you leave the room and close the door (at the closing brace }), everything inside is effectively recycled or forgotten.
In a standard do-while loop, the code inside the braces executes first, and then the condition inside the while( ) parentheses is checked. You might assume that because the condition is part of the loop, it can see what happened inside the braces. However, in C, the while check actually sits outside the room.
The Visibility Wall
Because the while condition is technically outside the block of code it controls, it cannot "see" any variables declared between the { and }. If you try to use a variable inside the while parentheses that was birthed inside the do block, the compiler will panic and tell you the variable is undefined.
To make a variable accessible to the loop's condition, you must declare it before the do keyword. This places the variable in an "outer room" that both the loop body and the condition can see.
Code Example: The Wrong Way vs. The Right Way
Here is a common mistake that leads to a compiler error:
// THIS WILL NOT COMPILE
do {
int secret_code = 42; // Variable born inside the room
} while (secret_code != 42); // Error! The condition can't see inside the room.
To fix this, we move the declaration outside the loop's "walls":
#include <stdio.h>
int main() {
int input; // Declared OUTSIDE the loop
do {
printf("Enter 0 to quit: ");
scanf("%d", &input); // Updating the existing variable
} while (input != 0); // Success! The condition can see 'input'.
return 0;
}
By declaring input before the do, it stays "alive" long enough for the while statement to check its value. If you only need a variable for a quick calculation inside the loop and don't need to check it in the condition, you can keep it inside. But for the condition itself, you must look outside.
Key takeaway
Variables declared inside a do-while block are destroyed at the closing brace, making them inaccessible to the loop's while condition.