in Programming in C edited by
11,916 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);  
 }
in Programming in C edited by
11.9k views

5 Answers

20 votes
20 votes
Best answer
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

1 comment

passed as reference so there is change only in the second function
2
2
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

3 Comments

edited
I think there is a typing mistake by gate2015, it should be 5-4-6=-5 rather than 5-6-4=-5.
5
5
the given program  f2 is call by referance

f2 does not support call by reference in c.
0
0
$f2$ is not “call by reference”, $\text{C}$ only supports call by value. $f2$ is call by value, the value being the address of variable $b$ and $c.

Using pointers it mimics the behaviour of call by reference.
0
0
8 votes
8 votes

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

by
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