Open In App

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

Last Updated : 05 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, returning a local variable from a function may result in an error due to the deallocation of variable memory after some value is returned from the function. But there are some ways using which we can safely return the local variables or the address of local variables and manipulate the data from the caller function.

In this article, we will discuss the various methods to return local variables from a function in C++.

What are Local Variables?

Local variables are those variables that are declared inside a block or function. Their scope is limited to that block and their lifetime is till the end of the block i.e. they are created when program control comes to the block and deleted when the program control goes out of the block

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

All the local variables of a function are stored inside the stack. This stack is removed when some value is returned by the function and all the function data is deleted. So, if we try to access the local variable after some value is returned by the function, the segmentation fault occurs.

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




// C++ program to illustrate the segementation fault caused
// due to accessing local varaible after function ends
#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

4195974

Output

Segmentation Fault (SIGSEGV)

How to return a local variable from a function?

There are two ways to access the local variables or array of a function after the function execution.

1. Static Variables or Static Arrays

The lifetime of the static variables is different from the lifetime of the local variables. Static variables live throughout the program Hence, if we make the local variables static, we can access it even after the function ends.

Example

C++




// Program to demonstrate how to return
// static variables from a function
#include <iostream>
using namespace std;
 
int& getStaticVariable()
{
    // Static variable
    static int staticVar = 10;
 
    // Returning Static variable
    return staticVar;
}
 
int main()
{
    int& result = getStaticVariable();
    cout << "Value of static variable: " << result << endl;
 
    // Modifying the static variable
    result += 10;
    cout << "Updated value of static variable: " << result
         << endl;
 
    return 0;
}


Output

Value of static variable: 10
Updated value of static variable: 20

2. Dynamic Variables and Arrays

Dynamic Variables and arrays are allocated memory on the heap. Unlike statically created variables, the lifespan of memory allocated on the heap exists until it is deallocated explicitly using the free() function or delete operator. Hence, if we create the local variables dynamically, we return the variables from a function.

Example

C++




// Program to demonstrate how to return
// dynamic arrays from a function
#include <iostream>
using namespace std;
 
int* createDynamicArray(int size)
{
    // Dynamically allocate an array
    int* dynamicArray = new int[size];
    for (int i = 0; i < size; ++i) {
        // Set values in the array
        dynamicArray[i] = i * 2;
    }
    // Return the dynamically allocated
    // array
    return dynamicArray;
}
 
int main()
{
    // Create and get the dynamically allocated
    // array
    int* returnedArray = createDynamicArray(5);
 
    // Use the returned array
    for (int i = 0; i < 5; ++i) {
        cout << "Element " << i << ": " << returnedArray[i]
             << endl;
    }
 
    // Deallocate the dynamic array
    delete[] returnedArray;
 
    return 0;
}


Output

Element 0: 0
Element 1: 2
Element 2: 4
Element 3: 6
Element 4: 8

Conclusion

By creating the static variables or creating variables dynamically, we can access the local variables of a function even after the function returns some value. This is because the lifetime of static variables begins when the function is called in which it is declared and ends when the execution of the program completes. The dynamic variables are assigned memory on hep which is deallocated only when the memory is explicitly deallocated using the delete operator.

Related Articles:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads