Reputation: 403
I was doing this question and I have a doubt.
#include <stdio.h>
int main(void)
{
int fun (int);
int i=3;
fun(i=fun(fun(i)));
printf("%d\n",i);
return 0;
}
int fun ( int i )
{
i++;
return(i);
}
I have a doubt when it gets to
fun ( i = 5 )
What happens with this? Will the value of i go to 6 or it will be 5. According to me, it should be 6. But that is not the correct answer.
Upvotes: 0
Views: 116
Reputation: 21888
The result of the call to fun()
is not assigned to i
. Therefore 5
is expected, not 6
.
Upvotes: 1
Reputation: 1497
This is related to scope. In the function scope, variables defined in that scope or the parameters pass in does not any effect on outer scope variables, unless it is a pointer. So, the output of fun
will be assigned to i
in the fun(i = 5)
but the internal operations of fun
, do not effect the outer scope i
. So it stays as it is before fun
last call. The output is 5
.
Upvotes: 1
Reputation: 18252
In C, parameters are passed by value. The variable i
in the main function is actually different from the i
inside fun()
, because its value is copied when it is passed into the function.
When you call i = fun(fun(i))
, 5 is isassigned into i
in the main function. However, the call to fun(5)
that returns 6 does not assign its result back into i
, leaving it unchanged. When the output is printed, i
is still 5.
Upvotes: 6