How to Access a Local Variable from a Different Function in C++?
Last Updated :
12 Feb, 2024
In C++, local variables defined within a function in C++ are only available inside the scope of that particular function. In some situations, we may need to access these local variables in some other function. In this article, we will discuss how to access a local variable from a different function in C++.
Access a Local Variable from a Different Function in C++
In C++, pointers can be used to access any memory location. We can use this property to access the local variable outside the function. We can pass the address of the local variable to the function where we want to access it. This concept is used in the pass-by-reference method of argument passing.
C++ Program to Access a Local Variable from a Different Function
C++
#include <iostream>
using namespace std;
void modifyValue( int * ptr)
{
(*ptr) += 10;
}
int main()
{
int localVar = 5;
int * ptr = &localVar;
modifyValue(ptr);
cout << "Modified Value: " << localVar << endl;
return 0;
}
|
Output
Modified Value: 15
Notice that the function that the variable belongs to is still not completely executed (i.e. sill alive on the stack). Once some value is returned by the original function, the local variable will be destroyed and we wont be able to access it anymore.
To prevent that, we will use the static keyword to make the lifetime of the local variable till the end of the program.
C++ Program to Access a Local Variable from a Different Function
C++
#include <iostream>
using namespace std;
int * getValue()
{
static int localVar = 10;
return &localVar;
}
int main()
{
int * ptr = getValue();
cout << "Local Variable Value: " << *ptr << endl;
return 0;
}
|
Output
Local Variable Value: 10
Conclusion
Although utilising pointers to access local variables across functions offers flexibility, there are a few possible dangers to be aware of. These include dangling pointers, memory leaks and unintended modifications. So it is better to use other methods such as returning the value.
Share your thoughts in the comments
Please Login to comment...