Solution:
In programming, the scope of a variable is defined as the extent of the program code within which the variable can we accessed or declared or worked with.
Global and Local are the two types of variable scope. So what are these variables?
Global Variables: Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
Local Variables: Local variables are declared inside a block. Local variables can only be declared on in-between ‘{‘ and ‘}’ or inside a block. Moreover, this variable only accessible inside the block.
Coming to the second part of your question, why does this happen? Before that, have a look into the program below:
#include<iostream>
using namespace std;
void func()
{
// this variable is local to the
int weight=20;
}
int main()
{
cout<<"Weight is: "<<weight;
return 0;
}
I’ve declared a local variable weight, and trying to call it outside from the particular function. As we know the local variables are only accessible inside his function.
In this case, if we try to compile and run this program it will throw back the error:
Error: weight was not declared in this scope
I hope this helps.