Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are there any problems with this Boolean based C programming question?

I’m currently learning about the Boolean data type, and I’m wondering if the conditions in the if-else statements are complete…

#include <stdio.h>
#include <stdbool.h>
int main() {
    bool a = false, b = false, c = false , d = false;
    if ((a&&b)||(!c&&d)) {
        if(((a||!b)&&c)||(b&&!a)) {
            printf("1");
        } else if ((a||(d&&b))&& !b) {
            printf("2");
        } else {
            printf("3");
        }
    } else {
        if(!(d&&c)&&(!a)) {
            printf("4");
        } else {
            printf("5");
        }
    }
    return 0;
}

Shouldn’t the conditions in the if-else statements have a comparison? For example (a&&b)==true || (!c&&d)==true. Running the program as it is outputs a "4" and I’m a bit confused as to why. Thank you

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In order to understand how the code executes and gives the final result, the key is to understand the operator precedence.

Among the three logic operators, namely logic not !, logic and && ,and logic or ||, logic not ! has the highest precedence, the logic and && and then comes logic or ||.

The logic not ! has a higher precedence than logic and && and logic or ||, so the a&&b and !c&&d both evaluate to false.

Because (a&&b)||(!c&&d) evaluates to false, the outer if body doesn’t execute.

Now, it comes into the outer else section.

d&&c evaluates to false because both of d and c are false. As a result, !(d&&c) evaluates to true. Of course not a !a evaluates to true too.

In the end, !(d&&c)&&(!a) is true. So printf("4"); executes and output a 4

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading