In: Computer Science
Explain Parameter passing Semantics in Java/C++
There are two type or parameter passing semantics in java/c++
1. Pass by value
2. Pass by reference
1) Pass by value :- In the pass by value the original data are not modified, it will just copy the data which we will pass.
For example:-
#include <iostream>
using namespace std;
void pass(int value) {
cout << "Value passed by parameter into function: " <<
value << endl;
value = 20;
cout << "Value before function end: " << value <<
endl;
}
int main() {
int value = 10;
cout << "Value before calling : " << value <<
endl;
pass(value);
cout << "Value after calling: " << value <<
endl;
return 0;
}
/******************output**********************/
Value before calling : 10
Value passed by parameter into function: 10
Value before function end: 20
Value after calling: 10
--------------------------------
2) Pass by reference :- It will change the original value of the variable.
For Example:
#include <iostream>
using namespace std;
void process(int& value) {
cout << "Value passed by parameter into function: " <<
value << endl;
value = 20;
cout << "Value before function end: " << value <<
endl;
}
int main() {
int value = 10;
cout << "Value before calling : " << value <<
endl;
process(value);
cout << "Value after calling: " << value <<
endl;
return 0;
}
/****************output************************/
Value before calling : 10
Value passed by parameter into function: 10
Value before function end: 20
Value after calling: 20
--------------------------------
Please let me know if you have any doubt or modify the answer, Thanks :)