unexpected output in function calls
i have a program in which i have implemented main function as below and finally i getting a unexpected value of i.
int mai开发者_Python百科n()
{
int fun (int);
int i=3;
fun(i=fun(fun(i)));
printf("%d",i);
return 0;
}
and my function implementation is
int fun(int i)
{
i++;
return(i);
}
my output is:
5
what i expected was:
6
i = fun(i=fun(fun(i)));
This would give you 6
fun(i=fun(fun(i)));
This gives 5 because the last call does not assign the value to i.
Also as mentioned by Tom below i is being passed by value not reference, if you did pass by reference then it would be 6 if you did fun(fun(fun(&i)));
(depending on what parameter type the function takes/returns).
You are passing the argument by value, and returning that value. The variable i
is only modified during initialization (set to 3) and in the call to the outer fun
where it takes the value 5 returned from fun(fun(3))
EDIT C++ only (before @awoodland removed that tag from the question):
If you want to modify the external variable in the function you can do so by using references:
int& fun( int & x ) {
return ++x;
}
int main() {
int i = 3;
fun( fun( fun( i ) ) );
// fun( i = fun( fun( i ) ) ); // alternatively
}
i = 3;
fun(i=fun(fun(i)));
+
|
V
fun(i=fun(fun(3)));
+
|
V
fun(i=fun(4)); /* fun (3) returns 4 */
+
|
V
fun(i=5); /* fun (4) returns 5 and it is stored in i */
+
|
V
fun(5); /* fun (5) returns 6, but it is NOWHERE stored, i is still 5 */
print i results in 5 .
My guess is that your expectation comes from the i++
being convention for i = i + 1
and while that is true your issue here is scope. When you call a function in C like this add:
int add( int a, int b ) {
a = a + b;
return a;
}
you are passing by value. Which is to say that C is generating a duplicate of the values, thus you have a difference scope and thus things that happen inside of add
only affect the things inside of add.
The other method you can pass data around in C is by reference like this
int * add( int * a, int b ) {
(*a) = (*a) + b;
return a;
}
that function will mutate the memory pointed to by a*
and thus is "violating" it's scope. Using pass by reference you could have your function act in the manner you expected.
精彩评论