Skip to content
Related Articles

Related Articles

How to return local variables from a function in C++

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Jun, 2022
View Discussion
Improve Article
Save Article

The following article discusses the way to return a local variable created inside a function, which can be done by returning a pointer to the variable from the called function to the caller function.

What happens when you try to return a local variable as usual?

For example, in the following code, when the array is created inside a function and returned to the caller function, it throws a runtime error as the array was created in the stack memory, and therefore it is deleted once the function ends.

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to return an
// array
int* fun()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    return arr;
}
// Driver Code
int main()
{
 
    int* arr = fun();
    // Will cause error
    cout << arr[2];
 
    return 0;
}

Output

Segmentation Fault (SIGSEGV)

How to return a local variable from a function?

But there is a way to access the local variables of a function using pointers, by creating another pointer variable that points to the variable to be returned and returning the pointer variable itself. 

  • Returning a local variable:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return
// a pointer
int* fun()
{
    int x = 20;
    int* ptr = &x;
    return ptr;
}
// Driver Code
int main()
{
 
    int* arr = fun();
    cout << *arr;
    return 0;
}

Output

20

Note : Here, pointers works because the normal variables get stored in the stack which get destroyed after function ends. But, the pointers get stored in the heap and remain even after the fun call get over. So, we are able to access the value. 

  • Returning an array:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to return an
// array
int* fun()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    int *ptr = arr;
    return ptr;
}
// Driver Code
int main()
{
 
    int* arr = fun();
    cout << arr[2];
 
    return 0;
}

Output

3

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!