silentseeker
silentseeker

Reputation: 416

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

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

Upvotes: 2

Views: 982

Answers (3)

Sarwan
Sarwan

Reputation: 657

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."

Upvotes: 0

Eregrith
Eregrith

Reputation: 4366

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

Upvotes: 3

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158479

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.

Upvotes: 3

Related Questions