为什么这个函数不会陷入无限循环?
Why doesn't this function get stuck in an infinite loop?
这个函数来自我教授的笔记:
int ints_is_sorted_r(int* a, int n){
return n <= 1 || (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1));
}
这是我的版本,有很多 printfs 看看它的作用
int ints_is_sorted_r(int* a, int n){
printf("n <= 1 = %d\n",(n <=1));
printf("a[0] <= a[1] = %d <= %d\n",a[0],a[1]);
ints_println_special(a,n);
return n <= 1 || (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1));
}
(ints_println_special() 是我教授库中的一个函数,它打印整个数组)
我的问题是,递归如何停止?这是我测试的输出:
我的猜测是,当您有一个 OR 条件并且第一个条件为真时,它不会浪费时间寻找条件的右侧,因为它知道它无论如何都会为真。我说得对吗?
My guess is that when you have an OR condition and the first one is
true it doesn't waste time looking for the right side of the condition
because it knows it's going to be true anyway. Am I correct?
是的,你是对的!它叫做 "short-circuiting",Stack Overflow 上有几篇很好的帖子解释和讨论它,比如 this one。
PS:请注意,在 ||
运算符之后的部分内部也可能(可能会)存在这种短路;因此,在 (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1))
中,如果第一个比较 a[0] <= a[1]
是 FALSE
,则不会计算第二个,并且在这种情况下不会递归调用该函数。
这个函数来自我教授的笔记:
int ints_is_sorted_r(int* a, int n){
return n <= 1 || (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1));
}
这是我的版本,有很多 printfs 看看它的作用
int ints_is_sorted_r(int* a, int n){
printf("n <= 1 = %d\n",(n <=1));
printf("a[0] <= a[1] = %d <= %d\n",a[0],a[1]);
ints_println_special(a,n);
return n <= 1 || (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1));
}
(ints_println_special() 是我教授库中的一个函数,它打印整个数组)
我的问题是,递归如何停止?这是我测试的输出:
我的猜测是,当您有一个 OR 条件并且第一个条件为真时,它不会浪费时间寻找条件的右侧,因为它知道它无论如何都会为真。我说得对吗?
My guess is that when you have an OR condition and the first one is true it doesn't waste time looking for the right side of the condition because it knows it's going to be true anyway. Am I correct?
是的,你是对的!它叫做 "short-circuiting",Stack Overflow 上有几篇很好的帖子解释和讨论它,比如 this one。
PS:请注意,在 ||
运算符之后的部分内部也可能(可能会)存在这种短路;因此,在 (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1))
中,如果第一个比较 a[0] <= a[1]
是 FALSE
,则不会计算第二个,并且在这种情况下不会递归调用该函数。