There are two options for the function. Why the first does not work is understandable, but why then does the second one work?

The first:

int* f() { int b = 10; return &b; } 

Second:

 int* f() { int b = 10; int* a = &b; return a; } 
  • I hope you understand why you can't do this, right? - VladD 4:03 pm
  • Sorry, made a mistake. Not b, but & b - FanSin
  • one
    What do you mean by "triggered"? Both options are non-working. - VTT
  • We have two alternatives. Either the author of the question does not understand why it is impossible to return a link to a local variable, and someone should explain to him. Either the author of the question understands what he is doing, and then the meaning of the word “works” is unclear. - VladD pm
  • one
    @VladD, well, not that it is impossible to do that . You can do something, just need to understand well what exactly we want to do next with this address . - avp

3 answers 3

Okay, there are actually a few questions in your question.

First, your code, both its variants, is obviously incorrect, as local variables die along with the stack frame of the function in which they are defined.

Why is the first option not compiled? The compiler obviously sees that you are returning a pointer to a local variable, and gives an error (or, most likely, a warning).

Why, then, is the second option compiled? The fact is that the compiler is not obliged to catch you by the hand every time you make a mistake. It will not consider where the values ​​came from in all the variables that you return. If in the first case he helped you (because it was easy), then in the second he just decided not to do it (because he would have to analyze where the value of the variable a came from). C ++ is a language for adults, he believes that the programmer has read the documentation, understands what he is doing, and the compiler does not bother the programmer with excessive warnings.

Yes, why does the second option work? And by chance. You have accidentally stuck a variable in a memory draw on your stack. Nobody took away this very trite memory. And could take at any time. Just do not do this, otherwise there are no guarantees for the normal operation of the program.

If done according to the rules, the program will work. If you do not follow the rules, it may or may not work.

    Lucky. You have a variable stored on the stack. You return the address to the stack from the function. What lies at this address after exiting the function is unknown to anyone. In this case, it coincided that the value was not erased

      Because you are assigning a pointer value of 10.

      • Sorry, I was sleepy, or the mobile didn’t load, but it seemed to me that in the second case it was: int * a = b; - Valery