AlphaCodingSkills

C - Booleans


Advertisements

Previous Page Next Page

There are many instances in the programming, where a user need a data type which represents True and False values. For this, C has a bool data type, which takes either True or False values.

Boolean Values

A boolean variable is declared with bool keyword and can only take boolean values: True or False values. In the below example, a boolean variable called MyBoolVal is declared to accept only boolean values.

#include <stdio.h>
#include <stdbool.h>

int main (){
    bool MyBoolVal = true;
    printf("%i\n", MyBoolVal);         //returns 1 (true)

    MyBoolVal = false;
    printf("%i\n", MyBoolVal);         //returns 0 (false)
    return 0;
}

Output

1

0

Boolean Expressions

A boolean expression in C is an expression which returns boolean values: 1 (true) or 0 (false) values. In the below example, comparison operator is used in the boolean expression which returns 1 when left operand is greater than right operand else returns 0.

#include <stdio.h>

int main (){
    int x = 10;
    int y = 25;

    cout<<(x > y)<<"\n"; //returns 0 (false)
    return 0;
}

Output

0

A logical operator can be used to combine two or more conditions to make complex boolean expression like && operator is used to combine conditions which returns 1 (true) if all conditions are true else returns 0 (false). Please see the below example.

#include <stdio.h>

int main (){
    int x = 10;

    cout<<(x > 0 && x < 25)<<"\n"; //returns 1 (true)
    return 0;
}

Output

1

Previous Page Next Page