Why does call-by-value example not modify input parameter?
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()
.
The value of value
isn't changing because your int
that you pass to the function is being copied into the stack frame of the function, then it's being changed, and when the function exits the copy is destroyed. The original in main
's stackframe has not changed, since it was copied to the changeValue
.
If you want to change it, you should pass a reference to an int
, like so void changeValue(int& value)
, which says that the value isn't copied into the function, but merely an alias to the original is passed.