[英]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.在这段代码中,它是一个递归打印元素 1 到 5 的程序,当我使用
n--
而不是n-1
时,我得到一个堆栈溢出错误。 whereas when n-1
is used the code worked perfectly.而当使用
n-1
时,代码运行良好。 shouldn't n--
and n-1
work the same in this code?不应该
n--
和n-1
在这段代码中工作相同吗?
//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
. n--
返回n
的值,然后递减n
。 So in your case, it becomes an infinite loop because n
is never changing.所以在你的情况下,它变成了一个无限循环,因为
n
永远不会改变。 You can use --n
instead which decrement n
first, then returns the value of n
.您可以使用
--n
而不是先递减n
,然后返回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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.