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

前端 未结 6 578
栀梦
栀梦 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

    I'm including this answer as another way to think about writing functions and passing parameters by value.

    You could also have written this code in the following way. That is pass the parameter by value, modify the local copy in the function, which does not alter the original value, and return the altered value.

    int changeValue(int val)
    {
      val = 6;
      return val;
    }
    
    int main()
    {
    int value = 5;
    
    value = changeValue(value);
    
    cout << "The value is : " << value << "." << endl;
    
    return 0;
    }
    

    I am not in any way indicating my suggestion for your program is better than passing by reference. Instead, it is just the way learning a functional programming language (Clojure) is affecting the way I think.

    Also, in languages like Python, you cannot modify a scalar parameter. You can only return a new value. So my answer is more of an exercise in thinking about things differently in C/C++.

提交回复
热议问题