Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) );  
}
like image 644
silentseeker Avatar asked Mar 24 '26 07:03

silentseeker


1 Answers

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);
}
like image 127
Eregrith Avatar answered Mar 25 '26 21:03

Eregrith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!