3

Say you have a recursive method, and you post-increment/decrement a value in the recursive call. Why will this result in a stack overflow exception when a pre-increment/decrement will not?

Ex.

numberCount(currentNumber++); //Stack overflow exception

numberCount(++currentNumber); //No stack overflow exception

Thanks in advance for any clarification.

miku
  • 181,842
  • 47
  • 306
  • 310
Derrek Whistle
  • 701
  • 2
  • 7
  • 16

2 Answers2

12

The first

numberCount(currentNumber++); //Stack overflow exception

is equivalent to:

numberCount(currentNumber);
currentNumber += 1;

while the the second

numberCount(++currentNumber); //No stack overflow exception

is equivalent to

currentNumber += 1;
numberCount(currentNumber);

Need I explain more?

jlordo
  • 37,490
  • 6
  • 58
  • 83
  • I'd add that IMO, this is why you should always use the ++ operator on its own line (except in for loops). That way you don't have to think about this problem. – Daniel Kaplan Apr 19 '13 at 00:19
  • @DerrekWhistle: If the answer was helpful, please don't forget to accept it (checkmark next to it), and maybe even upvote it. – jlordo Apr 19 '13 at 00:21
  • I can't upvote until my rep increases, but i'll gladly accept it. – Derrek Whistle Apr 19 '13 at 00:23
0

In case of numberCount(currentNumber++);, if an Exception is thrown by numberCount function, will the variable currentNumber incremented?

Bud Damyanov
  • 30,171
  • 6
  • 44
  • 52
Alagar
  • 1