The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+8 votes
2.3k views

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 
asked in Programming by Active (3.7k points)
retagged by | 2.3k views
+1
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 !!
+2
S1 and S4 are correct here.
0

@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 Answer

+15 votes
Best answer
S1 and S4 are correct. There won't be any runtime error for the given code using pass by reference.
answered by Veteran (355k points)
selected by
+1
Thanx @ Arjun for clearing this confusion.
0
Hi @Arjun sir , is there any typo in the question ? ia = 3 , ib = 8

so , if we pass ( &(ia) , &((ib)+5) ) , it should give 13 , 3 , right ?
+2
The second parameter is address of a temp variable. So, ib won't be changed by swap.
0
ok.. thanks sir :)
0
@Arjun sir how r u getting ia is pass by value and only ib is pass by reference?
+2
nopes, both are pass by reference. But ib is not passed- ib+5 is passed- which is a temp variable.
+1
Thanks :)
0
hello , i am really getting confused at this statement --> call swap(ia,ib+5)

since its mentioned that they are passed by ref, so does that statement mean

1. swap(&(ia),&(b)+5) or

2.swap(&(ia),&(a+5))

i guess that in C is swap(&a,&(a+5))
pls help
0

As https://www.cs.fsu.edu/~myers/c++/notes/references.html states.

This is illegal at least for C++.

I even tried running the code in C++. It throws a compilation error.

+1
@Nikhil For ib+5, reference of a temporary will be passed.

@asdfghjk You have the code you tried?
+1


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

37,996 questions
45,492 answers
131,517 comments
48,592 users