in Programming in C retagged by
6,635 views
15 votes
15 votes

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: 

  1. S1 and S2 
  2. S1 and S4 
  3. S3 
  4. S1 and S5 
in Programming in C retagged by
6.6k views

4 Comments

Answer this question please. According to me answer should be (B) but I found it (A) on the web. Explain how could that happen . Why a run-time error may creep in !!
1
1
S1 and S4 are correct here.
2
2

@Arjun Sir || @Bikram Sir

is below its C equivalent code ?

#include<Stdio.h>
void swap(int*,int*);
main()
{
 int ia=3,ib=8;
 printf("Before Call a=%d , b=%d\n\n",ia,ib);
 swap(&ia,&ib+5);
 printf("After Call a=%d , b=%d\n\n",ia,ib);
}
void swap(int *ix,int *iy)
{
 int *it;
 *it=*ix;
 *ix=*iy;
 *iy=*it;
}
1
1
Is this out of syllabus now??
0
0

2 Answers

16 votes
16 votes
Best answer
S1 and S4 are correct. There won't be any runtime error for the given code using pass by reference.
selected by
by

4 Comments

1
1

@Shubhgupta could you pls help me 

m not getting why we are considering second parameter as temp

0
0

@jk_1, because we are not passing address of ib we are passing ib+5 that will store in one temp location.

1
1
12 votes
12 votes
    call swap (ia, ib+5)

The first parameter is passed by reference. For the second parameter, ib isn't passed by reference; rather a temporary memory cell is passed, whose value if 8+5=13. Let's name it p.

p swaps with a, hence a gets the value 13; p gets the value 3. We'll never refer to p again now.

 

    print *, ia, ib 

This would print 13, 8 because ib was never passed by reference, its value stays intact.

 

$S_1$ and $S_4$ are correct



Line 1 and Line 2 won't generate a runtime error, as ints are being assigned to ints. So, $S_2$ and $S_3$ are incorrect.

And since $S_4$ is correct, $S_5$ is incorrect.

1 comment

Awesome explanation.😊
0
0
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