0

I'm trying to understand what's going on here;

int& FunkyStuff(int num){
    int val = num * 10;
    std::cout << "New value is: " << val << "\n";
    return num;
}

int main(){
    std::cout << FunkyStuff(10) << "\n";
    return 0;
}

So, when I compile this code without the printing the value within the FunkyStuff function, the main spits out a garbage value which I expect due to the fact that the val object is destroyed once leaving the scope. However, if I just compile the program as is above, the program outputs an expected value of 100 in both cases. What's going on here behind the scenes?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Vocaloidas
  • 360
  • 2
  • 17
  • Because it is [undefined behaviour](https://stackoverflow.com/questions/56979248/why-does-this-simple-program-result-in-puppies-puppies-puppies-to-the-console). – Quimby Dec 10 '20 at 10:43
  • 1
    You can always check the generated assembly to see why it "works": https://godbolt.org/z/f5fYrM. In my case, it didn't. – Daniel Langr Dec 10 '20 at 11:30

0 Answers0