C++ Tutorial C++ Advanced C++ Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ - Return Pointer from Function



A pointer is a variable which stores address of another variable. C++ allows to pass pointers to the function as well as return a pointer from a function. This can be achieved by declaring the return type of the function as a pointer. See the syntax below:

Syntax

ponter_return_type function_name(parameters) {
  statements;
}

//for example
int * MyFunction() {
  statements;
}

Please note that, it is not a good idea to return the address of a local variable outside the function as it goes out of scope after function returns. However, this feature is useful if the local variable is defined as static variable. A static variable do not goes out of scope even after function returns and preserves its values after each function call.

Example:

In the example below, a static variable is created inside the function and the function returns the address of that variable.

#include <iostream>
using namespace std;

int * MyFunction() {
  static int count = 0;
  count++;
  return &count; 
}

int main () {
  int * p;
  for(int i = 1; i <= 3; i++) {
    p = MyFunction();
    cout<<"Function returns: "<<p<<"\n"; 
    cout<<"Value of count: "<<*p<<"\n";    
  }
  return 0;
}

The output of the above code will be:

Function returns: 0x555944f53158
Value of count: 1
Function returns: 0x555944f53158
Value of count: 2
Function returns: 0x555944f53158
Value of count: 3

Example:

Consider one more example, where an array of 5 random variables is created inside a function and returns the address of first array element.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int * MyFunction() {
  static int rand_num[5];

  //initialize random seed
  srand (time(NULL));

  //generating 5 random number between 1 and 100
  for(int i = 0; i < 5; i++) {
    rand_num[i] = rand() % 100 + 1;
  }

  return rand_num;
}

int main () {
  int * p;
  
  p = MyFunction();
  for(int i = 0; i < 5; i++) {
    cout<<"(p + "<<i<<") = "<<p+i<<"\n"; 
    cout<<"*(p + "<<i<<") = "<<*(p+i)<<"\n";    
  }
  return 0;
}

The output of the above code will be:

(p + 0) = 0x55beb3d2c170
*(p + 0) = 16
(p + 1) = 0x55beb3d2c174
*(p + 1) = 98
(p + 2) = 0x55beb3d2c178
*(p + 2) = 34
(p + 3) = 0x55beb3d2c17c
*(p + 3) = 87
(p + 4) = 0x55beb3d2c180
*(p + 4) = 56

❮ C++ - Pointers

5