3k views

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 | 3k views

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
}

by Boss (18.9k points)
selected by
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.
by (139 points)
edited by
+4
I think there is a typing mistake by gate2015, it should be 5-4-6=-5 rather than 5-6-4=-5.
0
the given program  f2 is call by referance

f2 does not support call by reference in c. Here is the solution what I think would be correct but hey I may be wrong .. by Active (1.9k points)
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.
by (429 points)
edited