Variable Scope
Variable Scope
Scope
Differentiate between global and local scope
Local Scope
Take a look at the code below. The first function declares the variable
my_var and then prints it. The second function also prints my_var. What do
you think the output will be?
void MyFunction1() {
string my_var = "Hello";
cout << my_var << endl;
}
void MyFunction2() {
cout << my_var << endl;
}
int main() {
MyFunction1();
MyFunction2();
return 0;
}
C++ returns an error such as error: ‘my_var’ was not declared in this
scope at the line containing cout << my_var << endl; within the second
function. This happens because variables declared inside a function have
local scope. Variables with local scope can only be used within that
function. Outside of that function, those local variables cannot be accessed.
In the image below, the light blue box represents the scope of my_var. Since
MyFunction2 (denoted in a light red box) is outside the scope of my_var, an
error occurs.
.guides/img/LocalScope
challenge
void MyFunction2() {
string my_var2 = "Hello";
cout << my_var2 << endl;
}
void MyFunction1() {
string my_var = "Hello";
cout << my_var << endl;
}
void MyFunction2() {
string my_var = "Bonjour";
cout << my_var << endl;
}
int main() {
MyFunction1();
MyFunction2();
return 0;
}
challenge
void MyFunction3() {
string my_var = "Hola";
cout << my_var << endl;
}
.guides/img/GlobalScope
void SayHello() {
cout << greeting << endl; //can access global variable
greeting
}
int main() {
SayHello();
return 0;
}
void SayHello() {
greeting = "Bonjour";
cout << greeting << endl;
}
int main() {
SayHello();
return 0;
}
challenge
void SayHello1() {
greeting = "Bonjour";
cout << greeting << endl;
}
void SayHello2() {
cout << greeting << endl;
}
int main() {
SayHello1();
SayHello2();
return 0;
}
Notice how in the code above the functions SayHello1() and SayHello2()
end up printing the same output. The result of greeting within SayHello2()
is affected by the modification of greeting within SayHello1().
Global vs. Local Scope
void PrintScope() {
string my_var = "local scope";
cout << my_var << endl;
}
int main() {
PrintScope();
cout << my_var << endl;
}
void PrintScope() {
my_var = "local scope";
cout << my_var <<endl;
}
int main() {
PrintScope();
cout << my_var << endl;
}
challenge
int main() {
PrintScope(my_var);
cout << my_var << endl;
}
void PrintScope() {
kMyConstant = "I CAN'T CHANGE";
cout << kMyConstant << endl;
}
int main() {
PrintScope();
cout << kMyConstant << endl;
}
challenge