Conteúdo do Curso
C++ Functions
C++ Functions
Variable Scopes
Variable scope in C++ refers to the region or context within a program where a particular variable is visible and accessible. In other words, it defines where you can use a variable in your code and determines its lifetime.
Variables declared within a function have local scope. They are accessible only within the function or the block of code inside which they were declared. Local variables are created when the program enters the block where they are defined and destroyed when the block is exited.
Note
In C++, a code block is a set of statements enclosed within curly braces
{ }
.
Let's look at the following example:
main
#include <iostream> int myFunction() { // Create variable inside the function int localVar = 10; return localVar; } int main() { // Try to access the variable created inside function std::cout << localVar; }
We can see the following error message: error: ‘localVar’ was not declared in this scope
.
The variable localVar
was created inside the MyFunction()
function and was destroyed after its execution. As a result, in the main()
function, we are trying to access a non-existent variable and getting an error.
To use the value of localVar
we have to assign the return value of a function to a variable created inside the main
function:
main
#include <iostream> int myFunction() { // Create variable inside the function int localVar = 10; return localVar; } int main() { // Assign the result of the function to a new variable int functionResult = myFunction(); std::cout << functionResult; }
You may ask a completely logical question: How can we return a variable from a function if this variable is destroyed after the function completes?
Obrigado pelo seu feedback!