In C++ programming language, we can return a pointer from a function like any other data type. We have to declare return type of the function as pointer.
For Example :int* getEvenNumbers(int N){ /* Function Body */ }
Points to Remember
As we know that, local variables gets created when control enters a function and gets destroyed as soon as control exits from a function. We should not return pointer to a local variable because as soon as control returns from a function the memory pointed by pointer no longer contains data of local variable.
If we want to return pointer to a local variable then we should declare it as a static variable so that it retains it's value after control exits from function.
As we know that, local variables gets created when control enters a function and gets destroyed as soon as control exits from a function. We should not return pointer to a local variable because as soon as control returns from a function the memory pointed by pointer no longer contains data of local variable.
If we want to return pointer to a local variable then we should declare it as a static variable so that it retains it's value after control exits from function.
C++ Program to return a pointer from a function
#include <iostream> using namespace std; // This function returns an array of N odd numbers int* getOddNumbers(int N){ // Declaration of a static local integer array static int oddNumberArray[100]; int i, odd = 1; for(i=0; i<N; i++){ oddNumberArray[i] = odd; odd += 2; } // Returning base address of oddNumberArray array // As oddNumberArray is a static variable, it will // retain it's value even after function exits return oddNumberArray; } int main(){ int *array, counter; array = getOddNumbers(10); cout << "Odd Numbers\n"; for(counter=0; counter<10; counter++){ cout << array[counter] << " "; } return 0; }
Output
Odd Numbers 1 3 5 7 9 11 13 15 17 19