I have two piece of code to get the sum of arr element:
1.
int sum1(int arr[], int size)
{
if(size<0)
{
return 0;
}
else
{
return arr[size] + sum(arr, size-1);
}
}
2.
int sum2(int arr[], int size)
{
if(size<0)
{
return 0;
}
else
{
return arr[size] + sum(arr, --size);
}
}
The first one gives me the right answer but the second one gives the some garbage. the difference only is that, in second, I am passing --size but in first I am passing size-1.
I am not figuring out what is the difference between them even if I pass post decrement like size--, it crashes.
So someone please help me to understand the problem, I can understand that in case of post decrement it will always pass the same value(the original size of array), so it goes in the loop.
But what is the problem in pre-decrement, I debug the code but can't figure out, as in both the cases loop counts for recursive call are same and the value for size in all call in both cases are same.