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

走远了吗. 提交于 2019-12-02 06:35:22

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

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.

Sarwan

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

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