简体   繁体   中英

When I use "n--" instead of "n-1" why do I get stackoverflow error?

In this code which is a program to print elements 1 to 5 recursively, when I use n-- instead of n-1 , I am getting a stack overflow error. whereas when n-1 is used the code worked perfectly. shouldn't n-- and n-1 work the same in this code?

    //when using n--

    class PrintElements1to5
    {
        public static void main(String[] args)
        {
            recursivePrint(5);
        }
    
        static void recursivePrint(int n)
        {
            if(n<1)
                return;
            recursivePrint(n--);  
            System.out.print(n+" ");
        }
    }

output:

Exception in thread "main" java.lang.StackOverflowError
    //when using n=n-1
    class PrintElements1to5
    {
        public static void main(String[] args)
        {
            recursivePrint(5);
        }
    
        static void recursivePrint(int n)
        {
            if(n<1)
                return;
            recursivePrint(n-1);
            System.out.print(n+" ");
        }
    }

output:

1 2 3 4 5 

n-- returns the value of n first, then decrement n . So in your case, it becomes an infinite loop because n is never changing. You can use --n instead which decrement n first, then returns the value of n . Let's take a simpler example.

int x = 3;
System.out.println(x - 1); // prints 2, x is still 3
System.out.println(x--);   // prints 3, x becomes 2
System.out.println(--x);   // prints 1, x becomes 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM