Here is a recursive function -
private void printVar01(int t){
if(t != 0){
logp.info("o: " + t);
printVar01(t-1);
}
}
The same function with a slight modification -
private void printVar02(int t){
if(t != 0){
logp.info("o: " + t);
printVar02(t--);
}
}
If I pass in a integer value, like 4, printVar01 works as expected, where t decrements to 0 in successive recursive calls, eventually causing the program to exit.
With printVar02, t stays at value 4.
Why? I am assuming this has something to do with variable assignment and/or how values are passed to functions.
t-1 does not change t while t-- does.
t-1 gives you a new value without affecting the actual value of tt-- gives you t and then decreases the value of tI think printVar02 should work fine and in printVar01 the value remains the same.
For the comment of DoubleMa
actually 01 will works not 02, in 01 t is changing, but in 02 the function is calling itself before changing the value of T, he just need to use --t;
I also definitely suspect the recursive call.
If you mean printVar = printVar01 = printVar02.
If you are calling printVar recursively then t-1 will work as a recursive call. It will make it work and in t-- it will pass the same value, 4, every time as it's a postdecrement. Use predecrement, --t, instead.
Just use --t instead of t--:
private static void printVar02(int t){
if(t != 0){
logp.info("o: " + t);
printVar02(--t);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With