Is returning a local native array by reference an error?

I have this code:

1
2
3
4
5
auto getArr() -> int(&)[2]
{
	int arr[2] = {3,9};
	return arr;
}


the array arr should be destroyed at the exit from getArr() so the return value should return a dangling reference right?

Thanks!
Last edited on
yes, this is an error. Its not a syntax error, but it is still undefined behavior and incorrect to do.
try it in the compiler!


x3.cpp: In function 'int (& getArr())[2]':
x3.cpp:19:6: warning: reference to local variable 'arr' returned [-Wreturn-local-addr]
int arr[2] = {3,9};
^~~

if you make arr static, it is ok to do.
Last edited on
Topic archived. No new replies allowed.