Spontaneously Functional!

A function func2 is defined as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
inline void func1(int &x, int &y)
{
    x += y;
    y = x - y;
    x -= y;
}
int func2(int n)
{
    func1(n,n);
    return n;
}

An integer value (in the range of int ) is passed to func2 . Then which of the following is true?

A. There is only one such integer value which when passed as an argument to func2 will be equal to the value returned by it.

B. For all integer values, the value returned by func2 will always be equal to the argument.

C. Inline functions are not valid for functions with void return type, which means that func1 is not declared in a valid manner and counts for an error, therefore func1 won't work.

B None of the options are correct A C

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Inline functions are defined for functions with void return type. So, option C is incorrect .

func1 is a very familiar function. It involves the swapping of two integer values without using a third variable. Arguments are passed as a reference because the actual values have to be swapped.

1
2
x += y
/* x' = x + y */


1
2
y = x - y
/* y = x' - y = (x+y) - y = x */


1
2
x -= y
/* x'' = x' - y' = (x + y) - x = y */

x = x y = [ x + y ] x = y x'' = x' - y' = [x + y] - x = y

So by the end of the function, we find that final value of x x is the initial value of y y and vice versa. This shows that the values have been swapped successfully.

But this method won't be able to swap the values if the same variable is being passed to both the arguments of func1 . See:

Consider passing an integer n n to func2 . Then func1(n,n) will be executing in the following way:

1
2
x += y
/* n' = n + n  = 2n */

1
2
y = x - y
/* n'' = n' - n' = 0 */

1
2
x -= y
/* n''' = n'' - n'' = 0 */

n = n n = 0 n = 0 \implies n''' = n'' - n'' = 0 \implies \boxed{n''' = 0}

This means that the function won't swap the value with itself, but will be equal to 0 0 instead. For all integer values passed as an argument to func2 , the value returned by it will be always 0 0 . This leads us to assert the fact that option B is incorrect .

Therefore, it is clear that only when 0 0 will be passed to func2 , then only "the argument will be equal to the value returned by it. ( 0 0 )" . Hence, we can say that "There is only one such integer value which when passed as an argument to func2 will be equal to the value returned by it." . So, clearly, option A is correct .

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...