Home > Backend Development > C++ > body text

Why Does `changeValue(value)` Not Change `value` in C/C ?

DDD
Release: 2024-11-16 08:47:03
Original
301 people have browsed it

Why Does `changeValue(value)` Not Change `value` in C/C  ?

The Conundrum of Call-by-Value: Unraveling the Value Preservation Puzzle

In C/C , function parameters are inherently passed by value. This implies that a replica of the original variable is passed to the function, rather than the original variable itself. This behavior can lead to confusion, as illustrated by the following code snippet:

void changeValue(int value) {
  value = 6;
}

int main() {
  int value = 5;
  changeValue(value);

  cout << "The value is : " << value << "." << endl;

  return 0;
}
Copy after login

Upon executing this code, one might expect the output to be "The value is: 6." after the function call. However, surprisingly, the output remains "The value is: 5." The reason for this behavior lies in the intricacies of call-by-value.

When the function changeValue() is invoked, a copy of the value 5 is created and passed to the function. This means that within the function, the value 6 is assigned to the copy, leaving the original value of 5 untouched.

To rectify this issue and modify the original variable, one must resort to call-by-reference. This technique involves passing a reference to the original variable to the function. In this case, the function can then modify the original value, reflecting the changes in the calling function.

void changeValue(int& value) {
  value = 6;
}

int main() {
  int value = 5;
  changeValue(value);

  cout << "The value is : " << value << "." << endl;

  return 0;
}
Copy after login

Now, upon executing the code, the output will be "The value is: 6." This highlights the distinction between call-by-value and call-by-reference and the importance of choosing the appropriate one based on the intended behavior of the program.

The above is the detailed content of Why Does `changeValue(value)` Not Change `value` in C/C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template