0

I need to determine whether the syntax of:

int& f1(int i, int& j) { int& k = i; j+=i; return k; }

is correct.

I have tested it, and to my astonishment, it compiles.

My understanding, since our function f1 is of of type int& it cannot return local variables. By calling the function, I create a local variable i. When I set int& k = i, I am setting the memory space of k to that of i. Therefore k is a local variable and thus it should not compile, since local variable kis returned.

Any explanations are extremely helpful.

user9078057
  • 271
  • 1
  • 10
  • I get, as expected, a warning on your code: `warning C4172: returning address of local variable or temporary: i` (msvc 15). Even if it's compiles without errors, it's undefined behavior. – vahancho Mar 27 '19 at 11:22
  • "...it cannot return local variables." you can do all sorts of strange things in c++, but just because you can doesnt make them correct – 463035818_is_not_an_ai Mar 27 '19 at 11:23
  • also, note that returning a reference to a local variable is not a syntax error. The syntax of this code is fine – 463035818_is_not_an_ai Mar 27 '19 at 11:23

0 Answers0