这个函数来 self 教授的笔记:
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 条件并且第一个条件为 true 时,它不会浪费时间寻找条件的右侧,因为它知道无论如何它都会为 true。我说得对吗?
最佳答案
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?
是的,你说得对!它被称为“短路”,Stack Overflow 上有几篇很好的帖子解释和讨论了它,例如 this one .
PS:请注意,在||
之后的部分内部也可能(可能会)存在这种短路。运算符(operator);所以,在 (a[0] <= a[1] && ints_is_sorted_r(a+1, n-1))
,如果第一次比较,a[0] <= a[1]
,是FALSE
,那么第二个不会被计算,并且在这种情况下该函数不会被递归调用。
关于c - 为什么这个函数不会陷入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59240235/