Pass-by-value-Result? [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:29:01

问题:

Possible Duplicates:
pass by reference or pass by value?
Pass by Reference / Value in C++

Im having trouble with the pass-by-value-result method. i understand pass by reference and pass by value but im not quite clear on pass-by-value result. How similar is it to pass by value(assuming it is similar)?

here is the code

#include  #include  using namespace std;  void swap(int a, int b) {    int temp;     temp = a;     a = b;     b = temp; }  int main() {   int value = 2;   int  list[5] = {1, 3, 5, 7, 9};     swap(value, list[0]);    cout 

now the objective is to find out what is the value of "value" and "list" are if you use pass by value result. (NOT pass by value).

回答1:

If you're passing by value then you're copying the variable over in the method. Which means any changed made to that variable don't happen to the original variable. This means your output would be as follows:

2   1 1   3 2   5 

If you were passing by reference, which is passing the address of your variable (instead of making a copy) then your output would be different and would reflect the calculations made in swap(int a, int b). Have you ran this to check the results?

EDIT After doing some research I found a few things. C++ Does not support Pass-by-value-result, however it can be simulated. To do so you create a copy of the variables, pass them by reference to your function, and then set your original values to the temporary values. See code below..

#include  #include  using namespace std;  void swap(int &a, int &b) {    int temp;     temp = a;     a = b;     b = temp; }  int main() {   int value = 2;   int  list[5] = {1, 3, 5, 7, 9};     int temp1 = value;   int temp2 = list[0]    swap(temp1, temp2);    value = temp1;   list[0] = temp2;    cout 

This will give you the results of:

1   2 3   2 2   1 

This type of passing is also called Copy-In, Copy-Out. Fortran use to use it. But that is all I found during my searches. Hope this helps.



回答2:

Use references as your parameters instead such as:

void swap(int &a, int &b) {    int temp;     temp = a;     a = b;     b = temp; } 

a and b will now hold the actual value.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!