Returning a variable about to be destroyed in a function












0














j is destroyed when the function calls return



k is destroyed at the end of the enclosing brackets



If i pass in 9 for j, k is created and will be assigned 81



Returning k will set func1 which is a reference to an integer = k



Returning will immediately terminate the function



My question is, are k and j terminated at the return statement?



If they are func1 should reference nothing...



But i have tried to run this code and it works...



int& func1(int j){
int k = j*j;
return(k);
}









share|improve this question






















  • Possible duplicate of C++ Returning reference to local variable
    – Algirdas Preidžius
    Nov 19 '18 at 13:24






  • 1




    "But i have tried to run this code and it works..." "It works" is only one of (many) possible manifestations of undefined behavior. It may even continue to work, up until the point you decide to show your code to a potential client, when it might decide to stop working.
    – Algirdas Preidžius
    Nov 19 '18 at 13:26












  • This should also trigger a warning from the compiler depending on your compiler and warning level.
    – uceumern
    Nov 19 '18 at 13:50










  • @Algirdas Preidžius OMG you are so smart, can we be friends??
    – Jokaaa
    Nov 19 '18 at 14:31










  • What is the reason for it continuing to work, compiler had a memory lapse?
    – Jokaaa
    Nov 19 '18 at 14:33
















0














j is destroyed when the function calls return



k is destroyed at the end of the enclosing brackets



If i pass in 9 for j, k is created and will be assigned 81



Returning k will set func1 which is a reference to an integer = k



Returning will immediately terminate the function



My question is, are k and j terminated at the return statement?



If they are func1 should reference nothing...



But i have tried to run this code and it works...



int& func1(int j){
int k = j*j;
return(k);
}









share|improve this question






















  • Possible duplicate of C++ Returning reference to local variable
    – Algirdas Preidžius
    Nov 19 '18 at 13:24






  • 1




    "But i have tried to run this code and it works..." "It works" is only one of (many) possible manifestations of undefined behavior. It may even continue to work, up until the point you decide to show your code to a potential client, when it might decide to stop working.
    – Algirdas Preidžius
    Nov 19 '18 at 13:26












  • This should also trigger a warning from the compiler depending on your compiler and warning level.
    – uceumern
    Nov 19 '18 at 13:50










  • @Algirdas Preidžius OMG you are so smart, can we be friends??
    – Jokaaa
    Nov 19 '18 at 14:31










  • What is the reason for it continuing to work, compiler had a memory lapse?
    – Jokaaa
    Nov 19 '18 at 14:33














0












0








0







j is destroyed when the function calls return



k is destroyed at the end of the enclosing brackets



If i pass in 9 for j, k is created and will be assigned 81



Returning k will set func1 which is a reference to an integer = k



Returning will immediately terminate the function



My question is, are k and j terminated at the return statement?



If they are func1 should reference nothing...



But i have tried to run this code and it works...



int& func1(int j){
int k = j*j;
return(k);
}









share|improve this question













j is destroyed when the function calls return



k is destroyed at the end of the enclosing brackets



If i pass in 9 for j, k is created and will be assigned 81



Returning k will set func1 which is a reference to an integer = k



Returning will immediately terminate the function



My question is, are k and j terminated at the return statement?



If they are func1 should reference nothing...



But i have tried to run this code and it works...



int& func1(int j){
int k = j*j;
return(k);
}






c++






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 19 '18 at 13:20









Jokaaa

124




124












  • Possible duplicate of C++ Returning reference to local variable
    – Algirdas Preidžius
    Nov 19 '18 at 13:24






  • 1




    "But i have tried to run this code and it works..." "It works" is only one of (many) possible manifestations of undefined behavior. It may even continue to work, up until the point you decide to show your code to a potential client, when it might decide to stop working.
    – Algirdas Preidžius
    Nov 19 '18 at 13:26












  • This should also trigger a warning from the compiler depending on your compiler and warning level.
    – uceumern
    Nov 19 '18 at 13:50










  • @Algirdas Preidžius OMG you are so smart, can we be friends??
    – Jokaaa
    Nov 19 '18 at 14:31










  • What is the reason for it continuing to work, compiler had a memory lapse?
    – Jokaaa
    Nov 19 '18 at 14:33


















  • Possible duplicate of C++ Returning reference to local variable
    – Algirdas Preidžius
    Nov 19 '18 at 13:24






  • 1




    "But i have tried to run this code and it works..." "It works" is only one of (many) possible manifestations of undefined behavior. It may even continue to work, up until the point you decide to show your code to a potential client, when it might decide to stop working.
    – Algirdas Preidžius
    Nov 19 '18 at 13:26












  • This should also trigger a warning from the compiler depending on your compiler and warning level.
    – uceumern
    Nov 19 '18 at 13:50










  • @Algirdas Preidžius OMG you are so smart, can we be friends??
    – Jokaaa
    Nov 19 '18 at 14:31










  • What is the reason for it continuing to work, compiler had a memory lapse?
    – Jokaaa
    Nov 19 '18 at 14:33
















Possible duplicate of C++ Returning reference to local variable
– Algirdas Preidžius
Nov 19 '18 at 13:24




Possible duplicate of C++ Returning reference to local variable
– Algirdas Preidžius
Nov 19 '18 at 13:24




1




1




"But i have tried to run this code and it works..." "It works" is only one of (many) possible manifestations of undefined behavior. It may even continue to work, up until the point you decide to show your code to a potential client, when it might decide to stop working.
– Algirdas Preidžius
Nov 19 '18 at 13:26






"But i have tried to run this code and it works..." "It works" is only one of (many) possible manifestations of undefined behavior. It may even continue to work, up until the point you decide to show your code to a potential client, when it might decide to stop working.
– Algirdas Preidžius
Nov 19 '18 at 13:26














This should also trigger a warning from the compiler depending on your compiler and warning level.
– uceumern
Nov 19 '18 at 13:50




This should also trigger a warning from the compiler depending on your compiler and warning level.
– uceumern
Nov 19 '18 at 13:50












@Algirdas Preidžius OMG you are so smart, can we be friends??
– Jokaaa
Nov 19 '18 at 14:31




@Algirdas Preidžius OMG you are so smart, can we be friends??
– Jokaaa
Nov 19 '18 at 14:31












What is the reason for it continuing to work, compiler had a memory lapse?
– Jokaaa
Nov 19 '18 at 14:33




What is the reason for it continuing to work, compiler had a memory lapse?
– Jokaaa
Nov 19 '18 at 14:33












2 Answers
2






active

oldest

votes


















1















and it works...




No, it appears to work. The moment you try to access the reference returned by func1 you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc.






share|improve this answer





















  • Nice name, how do you come up with it
    – Jokaaa
    Nov 19 '18 at 14:29



















0















If they are func1 should reference nothing...




You are correct. Try using the reference some more time and you will see:



#include <iostream>

int& func1(int j) {
int k = j * j;
return(k);
}

int main() {
int& addr = func1(9);

for (int i = 0; i < 10; ++i) {
std::cout << addr << 'n';
}
}


Output:



81
2758456
2758456
2758456
2758456
2758456
2758456
2758456
2758456
2758456





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375545%2freturning-a-variable-about-to-be-destroyed-in-a-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1















    and it works...




    No, it appears to work. The moment you try to access the reference returned by func1 you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc.






    share|improve this answer





















    • Nice name, how do you come up with it
      – Jokaaa
      Nov 19 '18 at 14:29
















    1















    and it works...




    No, it appears to work. The moment you try to access the reference returned by func1 you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc.






    share|improve this answer





















    • Nice name, how do you come up with it
      – Jokaaa
      Nov 19 '18 at 14:29














    1












    1








    1







    and it works...




    No, it appears to work. The moment you try to access the reference returned by func1 you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc.






    share|improve this answer













    and it works...




    No, it appears to work. The moment you try to access the reference returned by func1 you enter the Undefined Behavior realm. At that point all bets are off, it could've printed out 42, printed out nothing, crash, eat your CMOS battery etc.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 19 '18 at 13:30









    Sombrero Chicken

    23.3k33077




    23.3k33077












    • Nice name, how do you come up with it
      – Jokaaa
      Nov 19 '18 at 14:29


















    • Nice name, how do you come up with it
      – Jokaaa
      Nov 19 '18 at 14:29
















    Nice name, how do you come up with it
    – Jokaaa
    Nov 19 '18 at 14:29




    Nice name, how do you come up with it
    – Jokaaa
    Nov 19 '18 at 14:29













    0















    If they are func1 should reference nothing...




    You are correct. Try using the reference some more time and you will see:



    #include <iostream>

    int& func1(int j) {
    int k = j * j;
    return(k);
    }

    int main() {
    int& addr = func1(9);

    for (int i = 0; i < 10; ++i) {
    std::cout << addr << 'n';
    }
    }


    Output:



    81
    2758456
    2758456
    2758456
    2758456
    2758456
    2758456
    2758456
    2758456
    2758456





    share|improve this answer


























      0















      If they are func1 should reference nothing...




      You are correct. Try using the reference some more time and you will see:



      #include <iostream>

      int& func1(int j) {
      int k = j * j;
      return(k);
      }

      int main() {
      int& addr = func1(9);

      for (int i = 0; i < 10; ++i) {
      std::cout << addr << 'n';
      }
      }


      Output:



      81
      2758456
      2758456
      2758456
      2758456
      2758456
      2758456
      2758456
      2758456
      2758456





      share|improve this answer
























        0












        0








        0







        If they are func1 should reference nothing...




        You are correct. Try using the reference some more time and you will see:



        #include <iostream>

        int& func1(int j) {
        int k = j * j;
        return(k);
        }

        int main() {
        int& addr = func1(9);

        for (int i = 0; i < 10; ++i) {
        std::cout << addr << 'n';
        }
        }


        Output:



        81
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456





        share|improve this answer













        If they are func1 should reference nothing...




        You are correct. Try using the reference some more time and you will see:



        #include <iostream>

        int& func1(int j) {
        int k = j * j;
        return(k);
        }

        int main() {
        int& addr = func1(9);

        for (int i = 0; i < 10; ++i) {
        std::cout << addr << 'n';
        }
        }


        Output:



        81
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456
        2758456






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 '18 at 13:26









        Stack Danny

        1,105319




        1,105319






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53375545%2freturning-a-variable-about-to-be-destroyed-in-a-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            Npm cannot find a required file even through it is in the searched directory