Passing by reference does not change the variable

前端 未结 2 1459
旧巷少年郎
旧巷少年郎 2020-12-22 01:12

I am trying to implement a function to change state of the menu, but my reference is lost when it leaves the function:

void gotoLowerlevel(Menu *item)
{
             


        
相关标签:
2条回答
  • 2020-12-22 01:43

    You're passing the pointer by value.

    Operations on the object it points to will be visible to the outside, but the pointer itself is only a copy.

    You might want to use a pointer to pointer.

    0 讨论(0)
  • 2020-12-22 01:50

    item in gotoLowerLevel is a local variable even if it is a reference to an object elsewhere. To modify cnsle->currentState you need to either:

    • pass in cnsle
    • pass in a reference to cnsle->currentState (that is change the method signature to Menu ** itemptr and the call parameter to &cnsle->currentState)
    • or return the new value from gotoLowerLevel and assign it: cnsle->currentState = gotoLowerLevel(cnsle->currentState)

    My preference would be the last option, as this makes it clear when reading the calling code that currentState may be modified.

    Others have explained how to pass a reference. Code for my preferred solutions is:

    Menu* gotoLowerlevel(Menu *item)
    {
        if (item->chld != 0x00) {
            item = item->chld;
        }
        return item;
    }
    
    /* .... */
    cnsle->currentState = gotoLowerlevel(cnsle->currentState);
    
    0 讨论(0)
提交回复
热议问题