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++
#include <bits/stdc++.h>
using namespace std;
int * fun()
{
int arr[5] = { 1, 2, 3, 4, 5 };
return arr;
}
int main()
{
int * arr = fun();
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++
#include <iostream>
using namespace std;
int & getStaticVariable()
{
static int staticVar = 10;
return staticVar;
}
int main()
{
int & result = getStaticVariable();
cout << "Value of static variable: " << result << endl;
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++
#include <iostream>
using namespace std;
int * createDynamicArray( int size)
{
int * dynamicArray = new int [size];
for ( int i = 0; i < size; ++i) {
dynamicArray[i] = i * 2;
}
return dynamicArray;
}
int main()
{
int * returnedArray = createDynamicArray(5);
for ( int i = 0; i < 5; ++i) {
cout << "Element " << i << ": " << returnedArray[i]
<< endl;
}
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:
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++ Code // C++ Program to Return a Local // Array from a fun
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
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 Content Pass Vector by ValuePa
5 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
strtol() function in C++ STL
The strtol() function is a builtin function in C++ STL which converts the contents of a string as an integral number of the specified base and return its value as a long int. Syntax: strtol(s, &end, b) Parameters: The function accepts three mandatory parameters which are described as below: s: s
4 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
list remove() function in C++ STL
The list::remove() is a built-in function in C++ STL which is used to remove elements from a list container. It removes elements comparing to a value. It takes a value as the parameter and removes all the elements from the list container whose value is equal to the value passed in the parameter of t
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