Home > Backend Development > C++ > body text

Why Doesn't Call-by-Value Modify the Original Variable?

DDD
Release: 2024-11-21 18:43:13
Original
784 people have browsed it

Why Doesn't Call-by-Value Modify the Original Variable?

Call-by-Value: Understanding the Limitations

Consider this call-by-value example where we attempt to modify the value of input parameters within a function:

#include <iostream>
using namespace std;

void changeValue(int value);

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

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

  return 0;
}

void changeValue(int value)
{
  value = 6;
}
Copy after login

Surprisingly, the output remains 5 despite our effort to change it to 6. This behavior stems from the fundamental principle of call-by-value in C/C .

The Essence of Call-by-Value

In call-by-value, a copy of the original variable is passed to the function as an argument. Any modifications made to this copy within the function remain confined to that local scope and do not affect the original variable.

In our example, the function changeValue receives a copy of value from main(). Any changes made to this copy do not impact the original value variable.

The Solution: Pass-by-Reference

To modify the original variable from within a function, we must employ pass-by-reference. In C/C , this is denoted as follows:

void changeValue(int &amp;value);
Copy after login

By using & in the function signature, we create a reference (alias) to the original variable. Any changes made to the reference also modify the original variable.

Pass-by-Reference Example

void changeValue(int &amp;value)
{
  value = 6;
}
Copy after login

Now, when we call changeValue in main(), a reference to value is passed to the function, allowing it to modify the original value:

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

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

  return 0;
}
Copy after login

In this scenario, the output correctly reflects the modified value: 6.

The above is the detailed content of Why Doesn't Call-by-Value Modify the Original Variable?. 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