即使参数是函数调用,C是否也使用短路评估?

我知道逻辑运算符会进行短路检查。 也就是说,如果存在类似A && B && C的语句,那么如果A为假,则不评估BC 但在BC是函数调用的情况下,这也是如此吗?

例如,此代码中的return语句:

 bool areIdentical(struct node * root1, struct node *root2) { /* base cases */ if(root1 == NULL && root2 == NULL) return true; if(root1 == NULL || root2 == NULL) return false; /* Check if the data of both roots is same and data of left and right subtrees are also same */ return (root1->data == root2->data && //I am talking about this statement areIdentical(root1->left, root2->left) && areIdentical(root1->right, root2->right) ); } 

是的,如果root1->data == root2->datafalse则不调用这些函数。

简单的检查是这样做:

 #include  #include  int main(void) { write(1, "z", 1); if ((1 == 0) && write(1, "a", 1) && write(1, "b", 1)) { write(1, "c", 1); } write(1, "d", 1); return (EXIT_SUCCESS); } 

如果我们查看草案C99标准部分6.5.13 逻辑AND运算符4段说( 强调我的 ), 逻辑和运算符将短路而不管操作数是什么。

与按位二元和运算符不同,&&运算符保证从左到右的评估; 在评估第一个操作数后有一个序列点。 如果第一个操作数比较等于0,则不计算第二个操作数

注意, 仅当第一个操作数为false才会计算第二个操作数。 另请注意,它保证了第一次评估后的左侧评估和序列点。

是的,在函数调用中也是如此。

 #include void main() { if(0&&printf("hello")) { printf("true"); } else printf("false"); } 

例如,考虑上面的代码,它将输出为false。 然而,在“if condition”中将0替换为1将输出为“hellotrue”。