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

前端 未结 6 569
栀梦
栀梦 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条回答
  •  Happy的楠姐
    2020-11-28 17:24

    When you pass a function argument by value a copy of the object gets passed to the function and not the original object.Unless you specify explicitly arguments to functions are always passed by value in C/C++.

    Your function:

    void changeValue(int value)
    

    receives the argument by value, in short a copy of value in main() is created and passed to the function, the function operates on that value and not the value in main().

    If you want to modify the original then you need to use pass by reference.

    void changeValue(int &value)
    

    Now a reference(alias) to the original value is passed to the function and function operates on it, thus reflecting back the changes in main().

提交回复
热议问题