c - 为什么这个函数不会陷入无限循环?

标签 c recursion short-circuiting

这个函数来 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() 是我教授的库中的一个函数,用于打印整个数组)

我的问题是,递归如何停止?这是我的测试的输出:

enter image description here

我的猜测是,当你有一个 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/

相关文章:

c - 如何在 C 中设置/翻转位域

c - c 中具有多维数据类型的多维数组

linux - shell脚本中的递归

java - skip() 方法是短路操作吗?

mysql - MySQL 短路 IF() 函数吗?

c - 重新发送所有传入的数据包

c - txt的一部分和txt的另一部分之间的值是多少?

java - 从递归到迭代

sql - 递归 CTE 以查找所有项目的所有祖先

c# - c# 吗??运算符(operator)短路?