Definition - A parameter is a variable / value that can be passed to / from the procedure.
Passing Parameters by Reference
Parameters can be passed to procedures by reference. When passing by reference, the address of the required data is passed to the procedure (rather than the actual value of the data).
Disadvantage of Passing Parameters by Reference
Passing by reference may lead to unintended side effects where the parameter has its value changed in the procedure (which then inappropriately affects its value in the main program).
Passing Parameters by Value
A parameter can also be passed by value. This is where a local copy of the data is created for the procedure (and discarded later).
Parameters can be passed by reference or passed by value, explain the difference below:
data1 = 5
data2 = 20
data3 = 30
function mult(byXXX num1 as integer, byXXX num2 as integer, byXXX num3 as integer)
num1 = num1 * num2 * num3
print (num1)
print (data1, data2, data3)
mult(data1, data2, data3)
print (data1, data2, data3)
a) What is the output when XXX is Ref?
Firstly, we print, which outputs 5, 20, 30. Then we call the function multi, and we pass data by reference. Inside the function, we mutliply 5, 20, 30 and store the result in num1, it also prints the output 3000 for num1. After we exit the function, we print the three variables again and we see that outputs 3000, 20, 30. That's because when we passed data1 to the function, we passed it by reference. A pointer to the data held in data1 was given to num1 and any changes that happened to num1 were also made to data1.
Outputs when we execute these lines of code:
print (data1, data2, data3) - 5, 20, 30
mult(data1, data2, data3) - 3000
print (data1, data2, data3) - 3000, 20, 30
b) What is the output when XXX is Val?
Firstly, we print which prints 5, 20, 30. Then we call the function and we pass data by value. Inside the function, we multiply 5, 20, 30 and store the result in a num1, it also prints the output 3000 for num1. After we exit the function, we print the variables again and we see that it prints 10, 20, 30. That's because when we passed myData to the function, we passed it by value. We passed a copy of the data in data1 to num1 so any changes that happened to num1 were now not made to data1.
Outputs when we execute these lines of code:
print (data1, data2, data3) - 5, 20, 30
mult(data1, data2, data3) - 3000
print (data1, data2, data3) - 5, 20, 30
In some books and websites you will see these names been used interchangably. However, a parameter is a variable in a subroutine definition. When a method is called, the arguments are the data you pass into the subroutine’s parameters.
public void MyMethod(string myParameter)
{
myParamater = “I’m a parameter” * 3;
}
/** main code **/
string myArg1 = "this is my argument";
myClass.MyMethod(myArg1);