Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Variable Scopes | Introduction
C++ Functions
course content

Зміст курсу

C++ Functions

C++ Functions

1. Introduction
2. Function Arguments Specification
3. Function Return Values Specification
4. Some Advanced Topics

bookVariable 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:

cpp

main

copy
1234567891011121314
#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:

cpp

main

copy
123456789101112131415
#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?

What is the lifetime of a local variable in C++?

What is the lifetime of a local variable in C++?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 4
some-alt