The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+10 votes
2.9k 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
asked in Compiler Design by Veteran (103k points) | 2.9k views

1 Answer

+18 votes
Best answer

Answer is C).

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).

answered by Veteran (50.2k points)
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? 

Answer:

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

40,845 questions
47,507 answers
145,768 comments
62,262 users