edited by
7,161 views
19 votes
19 votes

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 $\textsf{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$
edited by

2 Answers

Best answer
23 votes
23 votes

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

selected by
0 votes
0 votes

option c) 5, 20

//call by value
void foo(int x, int y)
{
    x += y;
    y += x;
}
int main()
{
    int x = 5.5;
    foo(x, x);
    printf("%d",x);
}
//output is 5

//call by reference
void foo(int *x, int *y)
{
    *x += *y;
    *y += *x;
}
int main()
{
    int x = 5.5;
    foo(&x, &x);
    printf("%d",x);
}
//output is 20

Answer:

Related questions

5 votes
5 votes
1 answer
1