(a) You are given the following code. Suppose formal parameters w, x, y, and z a
ID: 3830212 • Letter: #
Question
(a) You are given the following code. Suppose formal parameters w, x, y, and z are passed by value, by result, by value-result, and by reference respectively. There exists some problem(s) in the above code regarding parameter passing. Identify and describe all of them. (b) Give a concrete scenerio of writing a subprogram in which static local variables should be used. Your answer should described the semantics of your subprogram and provide justification of the need to use static local variables. Your answer should not be related to time and space efficiency.Explanation / Answer
a)
Pass By Value:
When we do pass by value, any change in the values done within foo will not affect these variables in the main function. In this case, when w,x,y,z were updated to new values, the values of a,b,c where not affected.
#include <iostream>
using namespace std;
void foo(int w, int x, int y, int z)
{
w = 11; x= 12; y = 13; z = z*2;
}
int main() {
int a = 1, b = 2, c = 3;
foo(a, b, b, 2*c );
cout<<"a="<<a<< ", b="<<b<<", c="<<c<<endl;
}
OUTPUT:
Pass By result:
When we are doing pass by result, we have to assign the result to some variable and also we can pass only one variable as result. If we want to update the variable values from the function then we have to send them all back in array as a return value and then assign the values back to a,b and c to update them in the main function.
Pass By value-result:
Same as above.
Pass By Reference:
Pass by referene will throw compiler error since the fourth parameter is not a variable whose memory is allocated, It is just a dynamically calculated value. i.e If we do the following
void foo(int &w, int &x, int &y, int &z)
{
w = 11; x= 12; y = 13; z = z*2;
}
then we will get the following error
But however we can do this,
#include <iostream>
using namespace std;
void foo(int &w, int &x, int &y, int z)
{
w = 11; x= 12; y = 13; z = z*2;
}
int main() {
int a = 1, b = 2, c = 3;
foo(a, b, b, 2*c );
cout<<"a="<<a<< ", b="<<b<<", c="<<c<<endl;
}
OUTPUT:
What happens here is, since we pass b twice the value of b is changed by both x and y and since y = 13 is executed last, b gets the value 13. Also c never gets altered since it is never passed as a reference variable at all.
b) Here is a function which checks if the number is less than 10, if so increases the counter by 1. This function uses a static local variable to know how many randomly generated numbers were less than 10.
int isCheck(int number)
{
static int counter = 0;
if(number<10)
counter++;
return counter;
}
int main() {
int timesCorrect = 0;
srand(NULL);
for(int i=0; i<10; i++)
{
timesCorrect = isCheck(rand()%20+1);
}
cout<<"Number of times number was less than 10: "<<timesCorrect<<endl;
return 0;
}
OUTPUT:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.