Functional-programming-call-by-reference

提供:Dev Guides
移動先:案内検索

関数型プログラミング-参照による呼び出し

参照による呼び出しでは、引数の参照アドレスを渡すため、元の値が変更されます。 実際の引数と形式的な引数は同じアドレス空間を共有するため、関数内の値の変更は、関数の内部だけでなく外部にも反映されます。

C ++の参照による呼び出し

次のプログラムは、C ++でCall by Valueがどのように機能するかを示しています-

#include <iostream>
using namespace std;

void swap(int *a, int *b) {
   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
   cout<<"\n"<<"value of a inside the function: "<<*a;
   cout<<"\n"<<"value of b inside the function: "<<*b;
}
int main() {
   int a = 50, b = 75;
   cout<<"\n"<<"value of a before sending to function: "<<a;
   cout<<"\n"<<"value of b before sending to function: "<<b;
   swap(&a, &b); //passing value to function
   cout<<"\n"<<"value of a after sending to function: "<<a;
   cout<<"\n"<<"value of b after sending to function: "<<b;
   return 0;
}

それは次の出力を生成します-

value of a before sending to function:  50
value of b before sending to function:  75
value of a inside the function:  75
value of b inside the function: 50
value of a after sending to function:  75
value of b after sending to function:  50

Pythonの参照による呼び出し

def swap(a,b):
   t = a;
   a = b;
   b = t;
   print "value of a inside the function: :",a
   print "value of b inside the function: ",b
   return(a,b)

# Now we can call swap function
a = 50
b =75
print "value of a before sending to function: ",a
print "value of b before sending to function: ",b
x = swap(a,b)
print "value of a after sending to function: ", x[0]
print "value of b after sending to function: ",x[1]

それは次の出力を生成します-

value of a before sending to function:  50
value of b before sending to function:  75
value of a inside the function:  75
value of b inside the function:  50
value of a after sending to function:  75
value of b after sending to function:  50