Why can I return a local variable from a function? Shouldn't local variables be deleted from the stack after function execution? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why can I return a local variable from a function? Shouldn't local variables be deleted from the stack after function execution?

See the example code. Why does it work? If I return a local variable, said variable shouldn't be available anymore after the function exits? Or am I missing something? https://code.sololearn.com/c9f2ZqaJxdqC/?ref=app

29th Nov 2018, 10:12 AM
Matthias Folte
Matthias Folte - avatar
2 Answers
+ 9
You are not returning the local variable, instead you are returning the value that is inside that variable. When value is returned, the variable gets deleted from the stack like you said.
29th Nov 2018, 2:16 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 2
Oh boy, I think I asked before thoroughly thinking about it. The result is returned by value, not by reference?
29th Nov 2018, 10:18 AM
Matthias Folte
Matthias Folte - avatar