edited by
11,921 views
35 votes
35 votes

The output of the following C program is_____________.

void f1 ( int a, int b)  {  
                int c; 
                c = a; a = b;
                 b = c;  
}   
void f2 ( int * a, int * b) {   
               int c; 
               c = * a; *a = *b; *b = c; 
} 
int main () { 
        int a = 4, b = 5, c = 6; 
        f1 ( a, b); 
        f2 (&b, &c); 
        printf ("%d", c - a - b);  
 }
edited by

5 Answers

Best answer
20 votes
20 votes
void f1 ( int a, int b)  {    //This code is call by value
// hence no effect of actual values when run.
                int c; 
                c = a; 
                a = b;
                b = c;  
}   
void f2 ( int * a, int * b) {   //*a= address of b 
//and *b = address of c
               int c;            //int c = garbage 
               c = * a;          //c = value at address a = 5;
               *a = *b;          //*a = Exchange original
// variable value of c to b = b= 6
               *b = c;             //*b = c = 5;
} 
int main () { 
        int a = 4, b = 5, c = 6; 
        f1 ( a, b);  This has no effect on actual values
// of a ,b since Call by value.
        f2 (&b, &c); Here change will be happen.
        At this point  int a = 4, b = 6, c = 5;
        printf ("%d", c - a - b);    = (5-4)-6 = 1-6 = -5
 }
selected by
36 votes
36 votes
Here, $f1$ will not change any values bcz it is call by value but $f2$ is call by reference and it swaps values of $b$ and $c$ and changes are also reflected in main function. So, $5-4-6= -5$ is the answer.
edited by
8 votes
8 votes

Here is the solution what I think would be correct but hey I may be wrong ..cheeky

4 votes
4 votes
Function f1 is for swapping but as parameters are passed by values so swapping of values will be done on former parameter (parameter local to f1) only not on actual parameter. So basically f1 is doing nothing here.

Function f2 is swapping values of b & c. As parameter are passed by reference ( addresses of actual variables are passed as parameter) so changes will reflect in actual variables also.
edited by
Answer:

Related questions

65 votes
65 votes
12 answers
2
31 votes
31 votes
2 answers
3