in Programming in C edited by
1,968 views
5 votes
5 votes

Consider the following program fragment:

var a,b : integer;
procedure G(c,d: integer);
begin
    c:=c-d;
    d:=c+d;
    c:=d-c
end;
a:=2;
b:=3;
G(a,b);

If both parameters to $G$ are passed by reference, what are the values of $a$ and $b$ at the end of the above program fragment ?

  1. $a=0$ and $b=2$
  2. $a=3$ and $b=2$
  3. $a=2$ and $b=3$
  4. $a=1$ and $b=5$
  5. None of the above
in Programming in C edited by
by
2.0k views

1 comment

I think this program fragment is Swapping Program.

As given value passed by reference then then Ans should be (B)

Correct me if i am wrong!!!
3
3

2 Answers

12 votes
12 votes
Best answer
Option B is correct as for the given inputs the program fragments does swapping of the values. Call-by-reference implies that the swapped values are reflected in the calling function as well.

PS: Procedure $G$ is not doing proper swapping for all input values as for negative values, there is a chance of underflow in $c - d.$
by

1 comment

It will cause overflow for some random values.

Ex: Let the integer size be 4 bits(just an assumption). a=maximum positive no. possible = 7 by considering 2’s complement representation and b= minimum negative no. possible = -8.

then c will definitely overflow. As a/c to our assumption, c-d=15 can’t be stored in our 4 bits.
0
0
2 votes
2 votes
Option b is right.

It is swapping the value of a and b .
Answer:

Related questions