Skip to content
Official PYQ · 2006

GATE CS 2006 Q56 — Programming in C

Explain with AI

Consider the following code written in a pass-by-reference language like FORTRAN and these statements about the code. 

subroutine swap(ix,iy) 
     it = ix 
L1 : ix = iy 
L2 : iy = it 
    end 
    ia = 3 
    ib = 8 
    call swap (ia, ib+5)
    print *, ia, ib 
    end 

S1: The compiler will generate code to allocate a temporary nameless cell, initialize it to 13, and pass the address of the cell to swap 
S2: On execution the code will generate a runtime error on line L1 
S3: On execution the code will generate a runtime error on line L2 
S4: The program will print 13 and 8 
S5: The program will print 13 and -2 

Exactly the following set of statement(s) is correct: 

Choose one option
View worked solution

Answer: B

To understand the behavior of the code, let's analyze how pass-by-reference handles different types of arguments (variables vs. expressions):

1. Handling of Arguments in Pass-by-Reference

  • Variables (L-values): When a variable like ia is passed, its actual memory address is passed to the subroutine. Any modification to the corresponding parameter inside the subroutine directly affects the original variable.
  • Expressions/Constants (R-values): When an expression like ib + 5 is passed, it does not have a persistent memory address. To handle this, the compiler allocates a temporary nameless memory cell, evaluates the expression (which is 8+5=138 + 5 = 13), stores this value in the temporary cell, and passes the address of this temporary cell to the subroutine. This validates statement S1.

2. Step-by-Step Execution Trace

Initially, we have:

  • ia = 3
  • ib = 8

When call swap(ia, ib + 5) is executed:

  1. A temporary cell (let's call it temp) is created with value 13.
  2. The address of ia is bound to parameter ix.
  3. The address of temp is bound to parameter iy.

Inside the subroutine swap(ix, iy):

  • it = ix: The local variable it gets the value of ix (which is ia, i.e., 33). So, it = 3.
  • L1: ix = iy: The variable ix (which is ia) is assigned the value of iy (which is temp, i.e., 1313). Thus, ia becomes 1313.
  • L2: iy = it: The variable iy (which is temp) is assigned the value of it (which is 33). Thus, temp becomes 33.

3. Final Output

After returning from the subroutine:

  • ia has been updated to 1313.
  • ib remains unchanged at 88 (since only the expression ib + 5 was passed using a temporary cell, not ib itself).

Thus, the print statement print *, ia, ib outputs 13 and 8. This validates statement S4.

Therefore, the correct statements are S1 and S4, which corresponds to option B.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions