Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 17 Jun, 2021

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
  • 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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :