Boolean Expressions

​Boolean Value

  • Logically

    • True

    • False

  • C++

    • Represented by an integer in the background

      • false is 0

      • true is literal 1 by default

        • any non-zero value is truthy

Where it is a problem

  • Some functions that are expected to be Boolean actually return an int.

    • int isalnum (int c);

    • check if character is alphanumeric (a decimal digit or an uppercase or lowercase letter)

  • What some students in the past have done

char c = 'z';
if(isalnum(c) == true) {
    //do something
}
//Dose not always work

Solution

  • Don't compare Boolean-ish functions with true or false.

    • Boolean-ish: return a value which is not strictly a Boolean value (e.g. int), but is used as if it returns a Boolean.

  • Just use the value directly as a Boolean without comparing it.

  • What you should do

char c = 'z';
if (isalnum(c)) {
    //do something
}
//Always works

Boolean Operators

  • And: &&

  • Or: ||

  • Not: !

Boolean Expressions

  • p && q is true if and only if both p and q are truthy (not 0/false)

    • && is Boolean AND

    • & is bitwise AND operation (does not produce a Boolean value)

  • P || q is true if and only if either p or q, or both , is truthy (not 0/false)

    • || is Boolean OR

    • | is bitwise OR operation (does not produce a Boolean value)

  • !p is true if and only if p is false

    • !p is false if and only if p is truthy (not 0/false)

    • ~ is bitwise negation (1's complement, does not produce a Boolean value)

Example

Boolean Operator-Notes

  • ! has highest precedence, followed by &&, then ||

  • If the value of an expression can be determined by evaluating just the sub-expression on left side of a logical operator, then the sub-expression on the right side will not be evaluated (short circuit evaluation)

Last updated

Was this helpful?