There are mainly 3 reason of error “ variable was not declared in this scope “.
- You have not declared a variable you are accessing in the program.
- You have mistyped the variable name.
- You are accessing the variable out of it’s scope.
Reason 1. You have not declared a variable you are trying to access.
If you had not declared a variable that you are accessing will cause this error. See the example below.
In the above example you can see that the variable Num was not declared so the error appeared.
To solve this error make sure you have declared the variable you are trying to access.
Reason 2. You have mistyped the variable name.
Because C++ is case sensitive language so you have to write the variable names carefully. Sometimes you may mistype a variable name when you are trying to access in program. See example below.
See in the above example variable Num has no scope because the variable declared above is num not Num.
Make sure you are accessing the variable with the exact name it was declared.
Reason 3. You are accessing the variable out of it’s scope.
Sometimes you may trying to access a variable out of its scope. It is because some variable are declared inside if statement , loops , functions etc. have local scope and these variables cannot be accessed outside of the scope. See example below.
Check In the above example the variable Num has no scope out of if statement because it was declared inside if block. So make sure you are accessing the variable in the scope it was declared.