When len is static, it’s not every call to length increment the same variable.
Here’s what happens
1->
2->
3->
4->
5
add 1 to length (length = 1)
add 2 to length (length = 3)
add 3 to length (length = 6)
add 4 to length (length = 10)
add 5 to length (length = 15)
return length + 1 (15 + 1)
16
When you use a local length (int length
), at each recursive call, length is set to 0 in this instance of the function.
0
solved Why does ‘static int’ give a different answer while recursively calculating the length of the linked list?