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.

0

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@DerrekWhistle: If the answer was helpful, please don't forget to accept it (checkmark next to it), and maybe even upvote it.
I can't upvote until my rep increases, but i'll gladly accept it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.