The Gateway to Computer Science Excellence
+23 votes
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);  
 }
in Programming by Boss (30.8k points)
edited by | 3k views

5 Answers

+11 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
 }
by Boss (18.9k points)
selected by
+34 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.
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.
+7 votes

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

by Active (1.9k points)
+3 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.
by (429 points)
edited by
+2 votes
answer is -5
by (47 points)
Answer:

Related questions

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
50,737 questions
57,321 answers
198,388 comments
105,140 users