Does C use short circuit evaluation even when arguments are function calls?

有些话、适合烂在心里 提交于 2019-12-02 07:52:03

问题


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?

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) );  
}

回答1:


Yes, the functions are not called if root1->data == root2->data is false.

Simple check is to do this:

#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);
}



回答2:


The Logical and operator will short circuit regardless of what the operands are, if we look at the draft C99 standard section 6.5.13 Logical AND operator paragraph 4 says(emphasis mine):

Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; there is a sequence point after the evaluation of the first operand. If the first operand compares equal to 0, the second operand is not evaluated.

Note, the second operand will not be evaluated only if the first is false. Also note it guarantees right to left evaluation and a sequence point after the first evaluation.




回答3:


yes, it is true in function calls also.

#include<stdio.h>
void main()
{
    if(0&&printf("hello"))
    {
        printf("true");

    }
    else 
        printf("false");
}

for example consider the above code, it will give output as false. However replacing 0 by 1 in "if condition' will give output as "hellotrue."



来源:https://stackoverflow.com/questions/19446465/does-c-use-short-circuit-evaluation-even-when-arguments-are-function-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!