How to return local variables from a function in C++
Last Updated :
05 Jun, 2023
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
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;
}
OutputValue 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;
}
OutputElement 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:
Similar Reads
How to Return a Local Array From a C++ Function?
Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C++ // C++ Program to Return a Local // Array from a function W
3 min read
How to pass or return a structure to/from a Function in C/C++?
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to pass structure as an argument to the functions? Passing of structure to the function can be done in two ways: By passing all the el
3 min read
Return From Void Functions in C++
Void functions are known as Non-Value Returning functions. They are "void" due to the fact that they are not supposed to return values. True, but not completely. We cannot return values but there is something we can surely return from void functions. Void functions do not have a return type, but the
2 min read
localtime() function in C++
The localtime() function is defined in the ctime header file. The localtime() function converts the given time since epoch to calendar time which is expressed as local time. Syntax: tm* localtime(const time_t* time_ptr); Parameter: This function accepts a parameter time_ptr which represents the poin
1 min read
C++ Return 2D Array From Function
An array is the collection of similar data-type stored in continuous memory. And when we are storing an array inside an array it is called 2 D array or 2-dimensional array. To know more about arrays refer to the article Array in C++. When there is a need to return a 2D array from a function it is al
4 min read
list front() function in C++ STL
The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. Syntaxlist_name.front(); Parameters This function
1 min read
basic_string c_str function in C++ STL
The basic_string::c_str() is a built-in function in C++ which returns a pointer to an array that contains a null-terminated sequence of characters representing the current value of the basic_string object. This array includes the same sequence of characters that make up the value of the basic_string
2 min read
Passing Vector to a Function in C++
To perform operations on vector belonging to one function inside other function, we pass this vector to the function as arguments during the function call.C++ provides three methods to pass a vector to a function in C++. Let's look at each of them one by one.Table of ContentPass Vector by ValuePass
5 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the a
2 min read
Computing Index Using Pointers Returned By STL Functions in C++
Many inbuilt functions in C++ return the pointers to the position in memory which gives an address of the desired number but has no relation with the actual index in a container of the computed value. For example, to find the maximum element in a code, we use std::max_element(), which returns the ad
3 min read