2

Here is a recursive funtion -

private void printVar01(int t){
    if(t != 0){
        logp.info("o: "+t);
        printVar01(t-1);
    }
}

Same funtion with a slight modification -

private void printVar02(int t){
    if(t != 0){
        logp.info("o: "+t);
        printVar02(t--);
    }
}

If I pass in a interger value like 4, printVar01 works as expected, where t decrements to 0 in successive recrsive 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 funtions.

Quest Monger
  • 7,642
  • 11
  • 34
  • 40

3 Answers3

3

t-1 does not change t while t-- does.

  • t-1 gives you new value without affecting the actual value of t
  • t-- gives you t and than decreases the value of t

I think printVar02 should work fine and in printVar01 value remains 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 than t-1 will work as recursive call will make it work and in t-- it will pass same value 4 every time as it's a postdecrement use predecrement --t instead.

Community
  • 1
  • 1
akash
  • 22,224
  • 10
  • 57
  • 85
  • 2
    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; – DoubleMa May 09 '15 at 03:42
2

just use --t instead of t--

private static void printVar02(int t){
if(t != 0){
    logp.info("o: "+t);
    printVar02(--t);
}
DoubleMa
  • 368
  • 1
  • 8
  • Yes this is right if method name is `printVar` and not `printVar02`. – akash May 09 '15 at 03:47
  • 1
    that what he meant, i got that when he said "Here is a recursive funtion" i'm sure he was just testing it that why he used 01 and 02 – DoubleMa May 09 '15 at 03:49
2

Post decrement decrees value by 1 after execution of statement printVar(t--). Hence each time 4 is being passed to the function.
Use should use --t instead which does the decrement first.

Raja
  • 831
  • 9
  • 22