Reputation: 5534
I am learning C and i come up with this example
#include <stdio.h>
int MyAdd(int);
main ()
{
int i;
int c = 0;
c = MyAdd(5);
printf("%d\n", c);
}
int MyAdd(int a)
{
if(a > 0)
return a + MyAdd(--a);
else
return 0;
}
I run this by my self and i calculate 15. (5 +4+3+2+1) but when i run it, i get 10... why??? At the 1st time, dont we get 5+ (do the func again) and etc..?
Upvotes: 0
Views: 151
Reputation: 1425
When used in expressions, side effect operators do funny, unexpected things, because you're basically at the mercy of the compiler.
In this case, your compiler is evaluating the second operand of a + MyAdd(--a)
before the first one. So, you're decrementing the variable before using it in the addition.
In any case, you don't really need the decrement operator. I would suggest rewriting the line as return a + MyAdd(a - 1);
.
Upvotes: 6
Reputation: 4951
Doing something like:
foo(a++) or
foo(++a)
Is not very safe because you depend on Compiler implementation - meaning if it reads arguments from left to right or right to left.
Lets consider the first case:
foo(a++)
If the compiler reads the arguments left to right the result will be call foo(a) and then a++. If the arguments are read right to left, the result will be call f(a+1)
Upvotes: 0