Why does call-by-value example not modify input parameter?

前端 未结 6 570
栀梦
栀梦 2020-11-28 16:51

In the following call-by-value example, I cannot understand why this code is not changing the value of the 5 to a 6.

Line 11 calls the function changeValue which ha

6条回答
  •  再見小時候
    2020-11-28 17:14

    The behavior being observed currently is because passing by value means a copy of value (new integer with value of value) is actually passed to the function.

    You have to pass by reference. For that the changeValue function will look like this:

    void changeValue(int& value)
    

    Rest of the code will remain the same.

    Passing a variable by reference means the same int value declared in main is passed to the changeValue function.

    Alternatively, you can pass a pointer to value to the changeValue function. That will however, require changes to how you call the function also.

    int main()
    {
        int value = 5;
    
        changeValue(&value);
    
        ...
    
        return 0;
    }
    
    void changeValue(int* value)
    {
        *value = 6;
    }
    

提交回复
热议问题