+ 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

24th Nov 2020, 2:57 AM
Prop de Puppy
Prop de Puppy - avatar
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
24th Nov 2020, 3:29 AM
Arsenic
Arsenic - avatar
+ 2
Thanks Bro Arsenic for this elegant solution, till now the best I think!!
24th Nov 2020, 7:23 AM
Prop de Puppy
Prop de Puppy - avatar
28th Nov 2020, 11:31 PM
Prop de Puppy
Prop de Puppy - avatar
28th Nov 2020, 11:38 PM
Prop de Puppy
Prop de Puppy - avatar
+ 1
Are there other solutions, anybody?
24th Nov 2020, 9:50 PM
Prop de Puppy
Prop de Puppy - avatar