Open In App

How to Access a Local Variable from a Different Function in C++?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate how to access local variable
// inside another function using pointers
#include <iostream>
  
using namespace std;
  
// Function to modify the value pointed to by a pointer
void modifyValue(int* ptr)
{
    // Dereferencing the pointer to modify the value
    (*ptr) += 10;
}
  
int main()
{
    int localVar = 5;
    int* ptr = &localVar; // Getting the address of the
                          // local variable
  
    // Passing the pointer to another function
    modifyValue(ptr);
  
    // Output the modified value
    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++




// C++ program to demonstrate how to access local variable
// inside another function using pointers
#include <iostream>
  
using namespace std;
  
// Function to modify the value pointed to by a pointer
int* getValue()
{
    static int localVar = 10;
    // Dereferencing the pointer to modify the value
  
    return &localVar;
}
  
// driver code
int main()
{
    int* ptr = getValue();
  
    // local variable value
    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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads