to understand what causes the error, you need to understand three things:
- the difference between defining a variable and using it.
first off, when you use a variable that was previously defined in your code, you don't mention the type again.
int x; // define x to be of type int
x = 10; // use x (in this case, set it to 10)
second, if you define a variable within a code block (between braces), the variable, the variable will stay available to use until control hits the closing brace of the block.
int x = 20;
// x = 10; // BOOM!!! x is no longer available
lastly, there is this thing called variable shadowing whereas you may define a new variable with the same type and name as an existing, in-scope variable, except that this has to be done in a more limited scope.
whenever you refer to the variable, using its name, in the more limited scope, you're gonna be referring to the new variable not the original one. in other words, the new variable shadows the original one in the more limited scope.
int x = 10; // defines original variable x
int x = 20; // defines new variable x (shadows original x)
printf("%d\n", x); // outputs 20 (i.e., x refers to new x)
} // new x is now dead (aka out of scope)
printf("%d\n", x); // outputs 10 (i.e., x refers to original x)
now the problem is that you're defining
query in the
else statement then control reaches the closing brace of the
else statement which gets
query, the variable that you just defined, to go out of scope. so basically you did nothing with that variable, hence, the compiler complaint!