+ 4
Why this program compiles and runs, but gives a crappy second result?
This program compiles and runs, but why the second result gives -nan or a crap result? And not the value 15? How to repair this program to get a good second result? I want make use of the pointer, don't want change into a normal variable!! https://code.sololearn.com/cz9a4MQIqM94/?ref=app
5 ответов
+ 4
In your function "treble()", you are returning reference of a local variable("result") whose lifetime extends inside the function only and using the memory address of the variable outside the lifetime area of the variable leads to undefined behaviour.
There are multiple ways to fix it, for example what I did is defined the variable "result" as static so that it retains its state even after returning from function
here is the fix👇
https://code.sololearn.com/c8R4ePIblE9O/?ref=app
+ 2
Thanks Bro Arsenic for this elegant solution, till now the best I think!!
+ 2
Found one other solution!!
https://code.sololearn.com/cR5mlPwggbH6/?ref=app
+ 2
I like the solution by Arsenic best!!
https://code.sololearn.com/cAzh28auWMOc/?ref=app
+ 1
Are there other solutions, anybody?