即使参数是函数调用,C也会使用短路评估吗? [英] Does C use short circuit evaluation even when arguments are function calls?
本文介绍了即使参数是函数调用,C也会使用短路评估吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道逻辑运算符会进行短路检查.也就是说,如果存在类似A && B && C
的语句,则如果A
为false,则不会评估B
和C
.但这在B
和C
是函数调用的情况下也是如此吗?
I know that logical operators do short-circuit checking. That is, if there is a statement like A && B && C
, then if A
is false, B
and C
are not evaluated. But is this also true in cases where B
and C
are function calls?
例如,此代码中的return语句:
For example, the return statement in this code:
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->data
是false
,则不会调用这些函数.
Yes, the functions are not called if root1->data == root2->data
is false
.
简单的检查就是这样做
#include <unistd.h>
#include <stdlib.h>
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);
}
这篇关于即使参数是函数调用,C也会使用短路评估吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文