Functional-programming-call-by-value

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

関数型プログラミング-値で呼び出す

関数を定義したら、目的の出力を得るために引数を渡す必要があります。 ほとんどのプログラミング言語は、関数に引数を渡すための*値による呼び出し*および*参照による呼び出し*メソッドをサポートしています。

この章では、C ++などのオブジェクト指向プログラミング言語およびPythonなどの関数型プログラミング言語での「値による呼び出し」の動作を学習します。

値による呼び出し方法では、元の値は変更できません。 引数を関数に渡すと、関数は引数としてスタックメモリにローカルに保存されます。 したがって、値は関数内でのみ変更され、関数外では効果がありません。

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 = 70;
   cout<<"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:  70
value of a inside the function:  70
value of b inside the function:  50
value of a after sending to function:  50
value of b after sending to function:  70

Pythonでの値による呼び出し

次のプログラムは、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

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

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

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:  50
value of b after sending to function:  75