0

I was doing some C# practice and decided to make a basic function to sum the contents of an integer array.

Originally I wrote my code as follows:

if(index == 0)
   return toSum[index];
else 
   return toSum[index] + sum(toSum, index--);

Now that code resulted in a StackOverFlow exception. This made no sense to me; surely this is how one would do a summation? Turns out the problem was in the index--. When I changed it to index - 1 it worked out fine, thus I was wondering why is that the case? My understanding is that it is simply a shorthand for index = index-1. I was wondering if anyone could explain the reason behind this behavior.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
SomeStudent
  • 2,856
  • 1
  • 22
  • 36
  • How did you check your understanding of what `index--` means? Did you look at a book or C# reference? – Paul Hankin Feb 11 '17 at 21:17
  • 1
    `--index` would be a shorthand for `index = index - 1`, but if there’s no point in changing the variable, why do it? – Ry- Feb 11 '17 at 21:17
  • Mostly going by what I recalled from the way they taught us about it in my freshman year programming class. It was in Java though as I trying to self-teach myself C#. My understanding for the longest of time was that index--, is short hand for index = index-1; – SomeStudent Feb 11 '17 at 21:18
  • (This operator works the same in C# and Java, note.) – Ry- Feb 11 '17 at 21:18
  • I think it just clicked, @Ryan. Since with a recursive call I guess you need --index since if the decrement is after it will never decrement correct? If I changed index-- to --index the function returns the correct result instead of overflowing. – SomeStudent Feb 11 '17 at 21:19
  • @SomeStudent: It’s not specifically about the recursion, just about the value you want. If index is 5, you want to pass 4 to the next `sum` call. You can get that value using `index - 1` or `--index` or `index -= 1` or `-(-index + 1)` or `index-- - 1`, but the first way is the only one that really makes sense. – Ry- Feb 11 '17 at 21:24

1 Answers1

2

Post-decrement operator returns the value before decrementing, so in your case the index will never be 0 and the function won't stop calling itself and you'll get a stack overflow. You want to write --index instead. It will return the value after decrementing then.

Szymski
  • 106
  • 1
  • 5