edited by
5,834 views
13 votes
13 votes

What will be the output of the following program assuming that parameter passing is

  1. call by value

  2. call by reference

  3. call by copy restore

procedure P{x, y, z}; 
begin 
    y:y+1; 
    z: x+x; 
end; 
begin 
    a:= b:= 3; 
    P(a+b, a, a); 
    Print(a); 
end  
edited by

1 Answer

Best answer
19 votes
19 votes
  • Call by Value : 3
  • Call by Reference : 12
  • Call by Copy-Restore : 12

The $3$ parameter passing mechanisms are simulated in the following 'C' codes. 

PS: C language only supports Call by Value and even in the case of pointers, the value of the pointer is getting passed explicitly in a pointer variable. This is different from call by reference (say in C++) where this happens implicitly. The following code for Call-by-Reference and Call-by-copy-restore is just a simulation of the parameter passing behaviour and their implementation in any language need not be the same.

  1. Call by Value
    #include <stdio.h> 
    int foo(int x,int y,int z)
    { 
        y = y+1; 
        z = x+x; 
    } 
    int main(void)
    { 
        int a = 3; 
        int b = 3; 
        foo(a+b,a,a); 
        printf("%d",a); 
        return 0; 
    }  
    
  2. Call by Reference (Call by reference is simulated by passing address in C) :
    #include <stdio.h>
    int foo(int *x,int *y,int *z)
    { 
        *y = *y+1; 
        *z = *x+*x;
    } 
    int main(void) 
    { 
        int a = 3; 
        int b = 3; 
        int c = a+b; 
        foo(&c,&a,&a); 
        printf("%d",a); 
        return 0; 
    }   
    
  3. Call by Copy-Restore:
    #include <stdio.h> 
    void foo(int *x,int *y,int *z)
    { 
        *y = *y+1; 
        *z = *x+*x;
    } 
    int main(void)
    { 
        int a=3; 
        int b=3; 
        int c=a+b; 
        int d,e;
        d = c;//copy 
        e = a;//copy 
        foo(&d,&e,&e); 
        a = e;//restore 
        c = d;//restore 
        printf("%d",a); 
        return 0;
    }
selected by

Related questions

22 votes
22 votes
3 answers
1