0

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..?

yaylitzis
  • 5,354
  • 17
  • 62
  • 107

2 Answers2

6

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);.

João Mendes
  • 1,719
  • 15
  • 32
  • 1
    No, you have 4 + (3 + (2 + (1 + (0 + (0))))). With the compiler you are using, the decrement and the function call is running *before* the value of a is determined for the addition. – João Mendes Nov 15 '13 at 11:17
  • Yes, I do, and no, you didn't understand it. I didn't mean that it was doing the decrement part before doing the function call. That, you *have* to do. I meant it was doing the `MyAdd(--a)` part before evaluating the `a +` part. If you do the function call before the decrement, all you get is (5 + (5 + (5 + (5 + ..., and ultimately, a stack overflow and subsequent segfault. – João Mendes Nov 18 '13 at 11:04
  • ok... i just posted a question , paste the solution there to accept it! :) @JoãoMendes – yaylitzis Nov 18 '13 at 11:06
  • Done, as requested. :) – João Mendes Nov 18 '13 at 11:08
0

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)

Pandrei
  • 4,843
  • 3
  • 27
  • 44