In C++
void func( int& num1, int* num2)
{
int temp = *num2;
*num2 = num1;
num1 = temp - *num2;
}
Given the function definition above what would be the result of the following code?
int val1 = 5;
int val2 = 8;
func(val1, &val2);
cout << val1 << “,” << val2 << endl;
Answer
a) 13, 8
b) 8, 13
c) An error message
d) 3, 5
e) 8, 5
void func( int& num1, int* num2)
{
int temp = *num2;
*num2 = num1;
num1 = temp - *num2;
}
Given the function definition above what would be the result of the following code?
int val1 = 5;
int val2 = 8;
func(val1, &val2);
cout << val1 << “,” << val2 << endl;
Answer: d. 3,5
Explanation:
//here func takes the address of val1 and the reference to the
address of val2 as parameters
void func( int& num1, int* num2)
{
//now &num1 will have the address of val1 and num2
will have the address of val2
int temp = *num2;//temp will point to the value in num2 i.e.,
8
*num2 = num1; //num2 will point to the value in num1
i.e., 5
num1 = temp - *num2; //now num1 8 - 5 i.e, 3
//finally num1 will have the value 3 and num2 will
have the value 5
}
int main()
{
int val1 = 5;
int val2 = 8;
func(val1, &val2); //pass val1 and address of val2
to func
cout << val1 << ","<< val2 <<
endl; //prints 3 and 5
return 0;
}
Output:
Get Answers For Free
Most questions answered within 1 hours.