When n is lower or equal than 2 the value 0 is returned. (Negative does not enter loop, 1 and 2 results in i
=0) When larger than 2 the value of i experiences rapid growth because of the line i = i*(i-1)
, until it overflows. If the overflow result - 1 (because of i--) is positive, the loop continues with the new i
. Because the test condition is valid, the rapid growth continues inevitably and results in more and more overflows which will eventually result in number that when decreased 1 value (i--) is a zero or a negative and then the test condition cannot be passed, the for loop ends and i
is returned.
Thus positive values cannot be returned, but i
could have been the result of a positive overflow result (when the overflow results in 1 and is decreased to 0 by i--).
Observing the special case of aa(8)
First of all aa(8) is called.
int i is created and assigned the value of 0.
The for loop begins.
i becomes 8,
8 > 0 so we execute the commands inside the body and set i to 8*7=56
We reached the end of the for so we execute i--, i becomes 55,
Again we check the test condition and 55 > 0 so we execute the commands i = 55*54 again the for block is ended and we execute i-- so i = 2969,
We check the test condition and 2969 > 0 so we execute the commands, i = 2969*2968, we execute i-- so i=8881991.
8881991 > 0 so we execute body i = 8881991*8881990, now there is an overflow and i becomes a negative number, the number is then decreased by i--
but now the test condition i > 0 is false and the loop ends.
i is returned.
Result of an overflow
The result of an int overflow can be any of numbers in its range.
Let's say we start counting from zero to represent the said number.
The first number resulting from an overflow is:
cout << INT_MAX+1;
output: -2147483648 (INT_MIN)
We can count further from here so the result can be any of the numbers between INT_MIN & INT_MAX, test:
cout << INT_MAX+n
When n is in range [1 (INT_MIN), 1+INT_MAX+1(0 until here)+INT_MAX(maximum)]
Again we reach INT_MAX and we can continue counting like before...