I asked some days ago
#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;
}
why the result of this is 10 and not 15 and i get an answer
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 operator of a + MyAdd(--a) before the first one. So, you're decrementing the variable before using it in the addition.
Understood it! I was just playing with my code and I replace the --i
with i--
, my compiler didn’t get any error and when I run it I got Segmentation fault (core dumped)
and i am trying to understand why this happened.