Why doesn't C++ support functions returning arrays


Let us consider this following program,

 Live Demo

#include <iostream>
using namespace std;
int* Array() {
   int a[100];
   a[0] = 7;
   a[1] = 6;
   a[2] = 4;
   a[3] = 3;
   return a;
}
int main() {
   int* p = Array();
   cout << p[0] << " " << p[1]<<" "<<p[2]<<" "<<p[3];
   return 0;
}

In this program,We get warning as,

Output

In function 'int* Array()':
warning: address of local variable 'a' returned [-Wreturn-local-addr]
int a[100];

We return the address of local variable but this is not possible as local variable may not exist in memory after the end of function call. So, C++ doesn’t support function returning arrays.

Updated on: 30-Jul-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements