Search code examples
cbooleanprintflogical-and

behavior of print function inside a Boolean expression


language: C

a bool expression outputs 0 if 0 is entered, else 1 will be the output.

following the above statement,

CASE 1:

input

#include <stdio.h>
#include <stdbool.h>
main()
{
    int a = 1,
        b = 2;
    bool res = ((a == b) && ("your "));
    printf("res = %d", res);
}

output

res = 0

CASE 2:

input

    bool res = (!(a == b) && ("your "));
    printf("res = %d", res);

output

res = 1

CASE 3: now i add prinf function to ("your ")

input

    bool res = ((a == b) && printf("your "));
    printf("res = %d", res);

output

res = 0 //adding printf doesn't change the output

CASE 4: input

    bool res = (!(a == b) && printf("your "));
    printf("res = %d", res);

output

your res = 1 // i expected just "res = 1" not "your res = 1"

how is the print function not executed in CASE 3 but executed in CASE 4?


Solution

  • According to the C Standard (6.5.13 Logical AND operator)

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

    In the expression used as an initializer in this declaration

    bool res = ((a == b) && printf("your "));
    

    the first operand (a == b) of the logical AND operator evaluates to 0. So the second operand that is the call of printf is not evaluated,

    On the other hand, in this expression used as an initializer in the declaration

    bool res = (!(a == b) && printf("your "));
     
    

    the first operand !(a == b) evaluates to 1. So the second operand that is the call of printf is also evaluated.