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
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++ C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
C Pointers A pointer is a variable that stores the memory address of another variable. Instead of holding a direct value, it has the address where the value is stored in memory. This allows us to manipulate the data stored at a specific memory location without actually using its variable. It is the backbone of
9 min read
Operator Overloading in C++ in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Classes and Objects In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read