In: Computer Science
Match each function type correctly.
Question 1 options:
|
|
Answers:
2. Pass By Reference
In this parameter type, the memory location of the variables from
the invoking function are passed
to the called function.
-> In this type of argument passing, what ever changes done to
the argument in the called function,
will be reflected in the calling function also as the same
variable's memory location is passed.
-> This is useful when the user wants to pass an array to a
function or.
-> This can also be used to return multiple values from the
called function to the calling function.
Ex :
void pass_by_reference(int *a) {
*a = 10;
}
int main() {
int x = 5;
printf("value of x : %d\n"); // 5 will be
printed
pass_by_reference(&x); //& is used to pass a
variable by reference
printf("value of x : %d\n"); // 10 will be
printed
}
1. Pass By Value
In this parameter type, a copy of the variables from the invoking
function are passed
to the called function.
-> In this type of arument passing, a copy of a original
variable is passed to the calling function,
hence the changes done to the variable inside the called function
are only visible inside the called
function and the original variable value will not be changed.
-> This is used when we do not want the called function to
change the original value of the variable.
Ex :
void pass_by_value(int *a) {
*a = 10;
}
int main() {
int x = 5;
printf("value of x : %d\n"); // 5 will be
printed
pass_by_value(x);
printf("value of x : %d\n"); // 5 will be
printed
}