
- Functional Programming Tutorial
- Home
- Introduction
- Functions Overview
- Function Types
- Call By Value
- Call By Reference
- Function Overloading
- Function Overriding
- Recursion
- Higher Order Functions
- Data Types
- Polymorphism
- Strings
- Lists
- Tuple
- Records
- Lambda Calculus
- Lazy Evaluation
- File I/O Operations
- Functional Programming Resources
- Quick Guide
- Useful Resources
- Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Functional Programming - Call By Reference
In Call by Reference, the original value is changed because we pass reference address of arguments. The actual and formal arguments share the same address space, so any change of value inside the function is reflected inside as well as outside the function.
Call by Reference in C++
The following program shows how Call by Value works in C++ −
#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; }
It will produce the following output −
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
Call by Reference in Python
The following program shows how Call by Value works in Python −
Live Demodef 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]
It will produce the following output −
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
Advertisements