3k views

Consider the following code fragment

void foo(int x, int y)
{
x+=y;
y+=x;
}
main()
{
int x=5.5;
foo(x,x);
}

What is the final value of x in both call by value and call by reference, respectively?

1. 5 and 16
2. 5 and 12
3. 5 and 20
4. 12 and 20

When a floating point constant is assigned to an integer value, it gets truncated and only the integer part gets stored.

Call by Value ===> whatever happens will happen in the called activation block in the stack and when we return it will not effect actual x so value will be 5.

Call by reference ===> A reference to original memory location is passed. So, in foo, x and y are aliases of the x in main (having same memory location). So, x in main will change and final value will be 20 (5+5 and 10+10).

selected by
+3

call by value

is 5

Call by reference

foo(5,5)

in foo( x=5 , y=5)
x=x+y //   5+5 = 10  therefore x store 10

y=y+x //  y initially has value =5 , geting added to modified value of x which is now , 10 therefore  y = 5 + 10  = 15
on exiting from this ffunction x and y are copied back to x finally 15 get stored in x .

answer i m getting as 5 and 15 .

What is wrong with my logic ??

+4
X and Y both hold the address of X . A change in one causes to change the value in other .
0

Kapil given value is 5.5 its a typo right?

+1 vote
1