-5

In this code making use of a-- and b++ shows Segmentation fault, but if am giving --a and ++b its working, why?!

add(a,b)
{ 
   if (a==0)
       return b;
    else
       return add(a--,b++); //why this line didn't work??! 
}
too honest for this site
  • 12,050
  • 4
  • 30
  • 52

3 Answers3

5

The post increment and decrement operators actually increment or decrement the values after the expression is evaluated, means it will change the values of a and b after they have been passed to the function.

This way you'll end up passing unchanged values of a and b to add () function all the time which will cause a stack overflow (causing the segmentation fault) as this is essentially a recursive function which never meets the returning condition.

OTOH, if you use pre-increment or decrement operator, the values of a and b will get decreased before they are passed to recursive add () call, thereby meeting the return condition, hence your program operates as expected.

That said, you should specify the return type of a function, for example, in this case, int.

Jens
  • 69,818
  • 15
  • 125
  • 179
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

Yes the issue is because you do a post increment/decrement, adding or subtracting AFTER going into the function. You actually go into an endless loop that probably gives you a segmentation fault.

Also, your function definition is wrong.

This should be your code:

int add(int a,int b)
{ 
   if (a==0)
       return b;
    else
       return add(--a,++b);
       //or
       //return add(a-1,b+1);    
}
Shlomi Agiv
  • 1,183
  • 7
  • 17
1

Segmentation fault relates to accessing memory outside of the allocated bounds. Currently, your function will cause a StackOverflow because the add function is called endlessly untill the stack pointer can no longer be pushed further.

There is most likely something else, which you didn't expose here, in your code that causes the SegmentationFault.

KnightsWatch
  • 114
  • 6