Programming Search⌘K

Conceptcore

Boolean type

Also called boolean, bool, Boolean, logical type, truth value, true and false, truthy, falsy, truthiness, LOGICAL.

The Boolean type has two values, true and false. Comparisons produce them, conditions consume them, and the operators and, or and not combine them.

Applies to
core-languages

Idea

A program must decide things: whether a file exists, whether a number is in range, whether a loop is done. The Boolean type holds the answer to such a question. It has exactly two values, true and false. A comparison such as n > 0 produces one of them, an if or a while uses one to choose what runs next, and the operators and, or and not build larger conditions from smaller ones.

# A Boolean has two values, and comparisons produce them.
print(3 < 5, 3 == 5, type(3 < 5).__name__)

# and, or and not combine Booleans.
print("a     b     and   or    not a")
for a in (False, True):
    for b in (False, True):
        print(f"{a!s:5} {b!s:5} {a and b!s:5} {a or b!s:5} {not a}")

# A condition decides which branch runs.
n = 7
if n % 2 == 1 and n > 0:
    print("positive and odd")

# Python also tests other values for truth: zero and empty values are false.
print([bool(v) for v in (0, "", [], None, 1, "0", [0])])
Output
True False bool
a     b     and   or    not a
False False False False True
False True  False True  True
True  False False True  False
True  True  True  True  False
positive and odd
[False, False, False, False, True, True, True]

3 < 5 is True and 3 == 5 is False, and both have the type bool. The table shows the rules of the three operators: and is true only when both operands are true, or is true when at least one is true, and not inverts its operand. The if statement runs its body because n % 2 == 1 and n > 0 is true. The last line shows a rule of Python and some other languages: a value of another type also has a truth value, so 0, "", [] and None count as false and "0" and [0] count as true.

How it works

Two values. "In computer science, the Boolean is a data type that has one of two possible values representing the two truth values of logic: true and false"1. The language references say the same. In Java, "The boolean type represents a logical quantity with two possible values, indicated by the literals true and false"2. In Go, "A boolean type represents the set of Boolean truth values denoted by the predeclared constants true and false"3.

Where Booleans come from and where they go. Comparison operators such as <, == and != produce Booleans, and so do functions such as isinstance and contains. Conditions consume them: if, while, for, the conditional operator ? : and assertions. Java states the rule strictly: "Only boolean and Boolean expressions can be used in control flow statements and as the first operand of the conditional operator ? :"2.

Operators. and (&&), or (||) and not (!) are the main operators. In most languages, && and || do not evaluate the right operand when the left one decides the result, so p != null && p.ok is safe. See short-circuit evaluation. Exclusive or is ^ in C, Java, C#, Go and Rust, or != on two Booleans. The bitwise operators & and | also work on Booleans in Java, C#, Rust and Python, but they evaluate both operands.

Truthiness. Some languages let a condition test a value of any type. Python says that "Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations"4, and that the false values include None, False, the zero of each numeric type and empty collections4. In JavaScript, "A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context"5, and every other value is truthy. C and C++ treat zero and the null pointer as false and other values as true. In C++, "The value zero (for integral, floating-point, and unscoped enumeration) and the null pointer and the null pointer-to-member values become false. All other values become true"6. Java, C#, Go and Rust have no truthiness: a condition must be a Boolean, so the program writes x != 0 or s != null.

Booleans and integers. In some languages a Boolean is a small integer. In Python, "bool is a subclass of int"4, so True + True is 2. In C, a comparison produces an int with the value 0 or 1, and the type bool holds only those two values. A conversion to bool is not a truncation: "(bool)0.5 evaluates to true, whereas (int)0.5 evaluates to 0"7. In other languages the types are separate. Java says that "No other casts on type boolean are allowed"2, and C# "provides only two conversions that involve the bool type", both of them to and from bool?8. Rust converts with as in one direction: "If you cast a bool into an integer, true will be 1 and false will be 0"9.

Storage. A Boolean needs one bit, but most languages store it in a byte, because a byte is the smallest unit that has an address. sizeof(bool) is 1 in C# and on the common C and C++ compilers, and size_of::<bool>() is 1 in Rust. Bit sets, bit fields and std::vector<bool> pack many Booleans into one word.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the type boolean and the literal types true and false, and the compiler accepts a value of any type in a condition, as JavaScript does. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has the type Boolean, and an if or a while needs a Boolean, so a number does not work as a condition. Boolean? holds null as well. No example file exists because kotlinc is not installed.
SQLNativeStandard SQL has the type BOOLEAN with TRUE, FALSE and UNKNOWN, and a comparison with NULL gives UNKNOWN, so WHERE uses three-valued logic. Some databases do not have the type. No example file exists.
BashIdiomBash has no Boolean values. A condition is the exit status of a command, where 0 means success, and true and false are commands that return 0 and 1. No example file exists.
PowerShellNativePowerShell has the .NET type bool with the variables $true and $false, and it converts other values in a condition, so 0, an empty string and $null are false. No example file exists because pwsh is not installed.
HTMLIdiomA Boolean attribute such as disabled, checked or required is true when it is present and false when it is absent, whatever its value is.
CSSDoes not applyCSS has no Boolean values. Media queries, container queries and @supports test conditions that are true or false.
Regular expressionsDoes not applyA regular expression matches text or does not match it, but the pattern language has no Boolean values.
Language Verdict Mechanism
Python native bool, a subclass of int; True and False; truth values for all objects
JavaScript native primitive boolean; Boolean() and !!; falsy and truthy values
TypeScript native boolean and the literal types true and false
Java native primitive boolean and the class Boolean; no conversion to or from int
Kotlin native Boolean; if needs a Boolean; Boolean? for a nullable value
C# native bool (System.Boolean); bool? with three-valued & and |
Go native bool; zero value false; no conversion to or from integers
Rust native bool; as converts it to an integer; then and then_some
C native C23 makes bool, true and false keywords; comparisons give int
C++ native bool; conversions from numbers and pointers; explicit operator bool
Bash idiom the exit status of a command: 0 is success and other values are failure; true and false are commands
PowerShell native [bool], $true and $false; conversion of other values by .NET and PowerShell rules
SQL native BOOLEAN with TRUE, FALSE and UNKNOWN, which is three-valued logic with NULL
Regex n/a a pattern matches or does not match, but there is no Boolean value
HTML idiom Boolean attributes such as disabled and checked are true when present and false when absent
CSS n/a no Boolean values; media queries and @supports give true or false conditions

Every general-purpose language has a Boolean type or an equivalent, so the verdict is native for all of them except Bash, which uses the exit status of commands. The languages differ in whether a condition accepts other types, in whether a Boolean is also an integer, and in how they convert text to a Boolean.

The example files show these differences. Python shows that True is 1, that 1 and True are the same dictionary key, how __bool__ and __len__ give an object a truth value, and that and and or return an operand. JavaScript lists all the falsy values and shows that a Boolean object is truthy, that [] == false is true, and the difference between || and ??. Java shows the x != 0 idiom, & and &&, Boolean.parseBoolean and a NullPointerException from a null Boolean. C# shows three-valued logic with bool?. Go parses Booleans with strconv and uses a map to bool as a set. Rust converts a bool to an integer with as, uses then_some and match, and parses only true and false. C shows that a comparison gives an int and that conversion to bool tests for zero. C++ uses explicit operator bool, std::boolalpha and the proxy of std::vector<bool>.

PythonGitHub
# bool is a subclass of int: True is 1 and False is 0.
print(True + True, sum([True, False, True]), isinstance(True, int), True == 1)

# So 1 and True are the same dictionary key.
print({1: "one", True: "true"})


# A class decides its truth value with __bool__ or __len__.
class Account:
    def __init__(self, balance):
        self.balance = balance

    def __bool__(self):
        return self.balance > 0


class Queue:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)


print(bool(Account(0)), bool(Account(5)), bool(Queue([])), bool(Queue([1])))

# and and or return one of their operands, not always a bool.
print(repr("" or "default"), repr("x" and 0), repr(None or []))

# bool() of any non-empty string is True, including "False".
print(bool("False"), "False" == str(False))

# all and any reduce many Booleans to one.
print(all([]), any([]), all(n > 0 for n in [1, 2, 3]), any(n > 2 for n in [1, 2]))
Output
2 2 True True
{1: 'true'}
False True False True
'default' 0 []
True True
True False True False
  • Verdict: native. bool is a subclass of int, so True + True is 2 and 1 and True are the same dictionary key. __bool__ and __len__ give an object a truth value. and and or return one of their operands, so "" or "default" is "default". bool("False") is True, because the string is not empty. all of an empty list is True and any of it is False.
#include <iostream>
#include <memory>
#include <print>
#include <vector>

// explicit operator bool works in a condition but does not convert to int.
struct Connection {
    bool open;
    explicit operator bool() const { return open; }
};

int main() {
    // A pointer, a number or a smart pointer converts to bool in a condition.
    int* p = nullptr;
    auto q = std::make_unique<int>(1);
    std::println("{} {} {}", static_cast<bool>(p), static_cast<bool>(q), static_cast<bool>(0.0));

    Connection c{true};
    if (c) std::println("connected");
    // int n = c; does not compile, because the conversion is explicit.

    // bool takes part in arithmetic as 0 or 1.
    bool t = true;
    std::println("{} {}", t + t, sizeof(bool));

    // Streams print 1 and 0 unless std::boolalpha is set.
    std::cout << true << ' ' << std::boolalpha << true << '\n';

    // std::vector<bool> packs bits, so an element is a proxy, not a bool&.
    std::vector<bool> bits(10, false);
    bits[3] = true;
    auto ref = bits[3];
    ref = false;
    std::println("{} {}", static_cast<bool>(bits[3]), bits.size());
}
Output
false true false
connected
2 1
1 true
false 10
  • Verdict: native. A null pointer, an owning unique_ptr and 0.0 convert to bool with static_cast. explicit operator bool lets Connection work in an if but not convert to int. true + true is 2. Streams print 1 for true until std::boolalpha is set. An element of std::vector<bool> is a proxy, so a copy of bits[3] still writes to the vector.
JavaGitHub
public class Main {
    static int calls = 0;

    static boolean check(boolean v) {
        calls++;
        return v;
    }

    public static void main(String[] args) {
        // boolean is its own type: no conversion from int, so the idiom is x != 0.
        int x = 5;
        boolean nonZero = x != 0;
        System.out.println(nonZero + " " + (x > 3 && x < 10) + " " + !nonZero);

        // && and || skip the right operand; & and | evaluate both.
        calls = 0;
        boolean a = check(false) && check(true);
        int shortCircuit = calls;
        calls = 0;
        boolean b = check(false) & check(true);
        System.out.println(a + " " + shortCircuit + " " + b + " " + calls);

        // ^ is exclusive or on booleans.
        System.out.println((true ^ true) + " " + (true ^ false));

        // Parsing accepts only "true", in any case; everything else is false.
        System.out.println(Boolean.parseBoolean("TRUE") + " " + Boolean.parseBoolean("yes") + " " + Boolean.parseBoolean("1"));

        // A Boolean object can be null, and unboxing null throws.
        Boolean maybe = null;
        try {
            if (maybe) System.out.println("unreachable");
        } catch (NullPointerException e) {
            System.out.println("NullPointerException");
        }

        // String concatenation and conversion.
        System.out.println("flag=" + true + " " + Boolean.toString(false) + " " + Boolean.compare(true, false));
    }
}
Output
true true false
false 1 false 2
false true
true false false
NullPointerException
flag=true false 1
  • Verdict: native. There is no conversion from int to boolean, so the idiom is x != 0. && evaluates one operand of check(false) && check(true), and & evaluates both. ^ is exclusive or. Boolean.parseBoolean accepts "true" in any case and gives false for "yes" and "1". Unboxing a null Boolean in an if throws NullPointerException.
#include <stdio.h>

int main(void) {
    /* In C23, bool, true and false are keywords. */
    bool flag = true;
    printf("%d %zu\n", flag, sizeof(bool));

    /* A comparison gives an int with the value 0 or 1. */
    int x = 5;
    printf("%d %d %zu\n", x > 3, x == 3, sizeof(x > 3));

    /* A condition treats any non-zero value as true. */
    if (x) {
        printf("non-zero is true\n");
    }

    /* Conversion to bool tests for zero, but conversion to int truncates. */
    double half = 0.5;
    int big = 256;
    bool b1 = half;
    int i1 = half;
    bool b2 = big;
    unsigned char c2 = big;
    printf("%d %d %d %d\n", b1, i1, b2, c2);

    /* !! turns any value into 0 or 1. */
    printf("%d %d\n", !!42, !!0);
    return 0;
}
Output
1 1
1 0 4
non-zero is true
1 0 1 0
1 0
  • Verdict: native. In C23, bool, true and false are keywords. A comparison has type int, so sizeof(x > 3) is the size of an int. A condition treats any non-zero value as true. Conversion to bool tests for zero, so 0.5 and 256 become 1, but conversion to int gives 0 and to unsigned char gives 0. !! turns any value into 0 or 1.
// bool has no conversion from int; a comparison gives a bool.
int x = 5;
bool nonZero = x != 0;
Console.WriteLine($"{nonZero} {x > 3 && x < 10} {!nonZero} {true ^ false}");

// bool? adds null, and & and | follow three-valued logic.
bool? unknown = null;
bool? t = true, f = false;
string Show(bool? v) => v?.ToString() ?? "null";
Console.WriteLine($"{Show(unknown & f)} {Show(unknown & t)} {Show(unknown | t)} {Show(unknown | f)}");

// Parsing and conversion.
Console.WriteLine($"{bool.Parse("True")} {bool.TryParse("yes", out var parsed)} {parsed} {Convert.ToBoolean(5)} {Convert.ToInt32(true)}");

// A bool takes 1 byte, and its default value is false.
Console.WriteLine($"{sizeof(bool)} {default(bool)}");
Output
True True False True
False null True null
True False False True 1
1 False
  • Verdict: native. A comparison gives a bool, and there is no conversion from int. bool? adds null, and & and | follow three-valued logic: null & false is False and null | true is True, but null & true and null | false are null. bool.TryParse("yes") fails, and Convert.ToBoolean(5) is True. sizeof(bool) is 1.
JavaScriptGitHub
// These are all the falsy values; every other value is truthy.
const falsy = [false, 0, -0, 0n, "", null, undefined, NaN];
console.log(falsy.map(Boolean).join(" "));
console.log([Boolean("0"), Boolean("false"), Boolean([]), Boolean({})].join(" "));

// Boolean() and !! convert a value to a primitive Boolean.
console.log(Boolean("text"), !!"text", !!0);

// A Boolean object is an object, so it is truthy even when it holds false.
const wrapped = new Boolean(false);
console.log(typeof wrapped, wrapped ? "truthy" : "falsy");

// == converts both sides to numbers, so these surprise.
console.log([] == false, "0" == false, null == false);

// || replaces every falsy value; ?? replaces only null and undefined.
const count = 0;
console.log(count || 10, count ?? 10);

// && and || return an operand, not always a Boolean.
console.log("a" && "b", "" || "default", typeof (1 && "x"));
Output
false false false false false false false false
true true true true
true true false
object truthy
true true false
10 0
b default string
  • Verdict: native. The example lists all eight falsy values, and "0", "false", [] and {} are truthy. Boolean() and !! convert a value to a primitive Boolean. new Boolean(false) is an object, so it is truthy. [] == false and "0" == false are true, but null == false is false. count || 10 replaces 0, and count ?? 10 keeps it.
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// bool is its own type: if needs a bool, and there is no conversion from int.
	x := 5
	nonZero := x != 0
	fmt.Println(nonZero, x > 3 && x < 10, !nonZero)

	// The zero value is false.
	var ready bool
	fmt.Println(ready)

	// strconv parses 1, t, T, TRUE, true, True and the false forms.
	for _, s := range []string{"true", "T", "1", "yes"} {
		b, err := strconv.ParseBool(s)
		fmt.Println(s, b, err != nil)
	}
	fmt.Println(strconv.FormatBool(true))

	// A map to bool is a set: a missing key gives false.
	seen := map[string]bool{}
	for _, w := range []string{"a", "b", "a"} {
		if seen[w] {
			fmt.Println("duplicate", w)
		}
		seen[w] = true
	}

	// Go has no conversion from bool to int, so it needs an if.
	count := 0
	for _, ok := range []bool{true, false, true} {
		if ok {
			count++
		}
	}
	fmt.Println(count)
}
Output
true true false
false
true true false
T true false
1 true false
yes false true
true
duplicate a
2
  • Verdict: native. A condition must be a bool, and the zero value is false. strconv.ParseBool accepts "true", "T" and "1" and returns an error for "yes". A map[string]bool works as a set, because a missing key gives false. Go has no conversion from bool to int, so counting the true values needs an if.
RustGitHub
fn main() {
    // bool is its own type: if needs a bool, and no other type converts to it.
    let x = 5;
    let non_zero = x != 0;
    println!("{} {} {}", non_zero, x > 3 && x < 10, !non_zero);

    // as converts a bool to an integer, but not the other way.
    println!("{} {}", true as u8, false as i32);
    let count = [true, false, true].iter().filter(|&&b| b).count();
    println!("{count}");

    // & and | evaluate both operands; && and || stop early. ^ is exclusive or.
    println!("{} {} {}", true & false, true | false, true ^ true);

    // then and then_some turn a bool into an Option.
    let age = 20;
    println!("{:?} {:?}", (age >= 18).then_some("adult"), (age < 13).then(|| "child"));

    // Parsing accepts only "true" and "false".
    println!("{:?} {}", "true".parse::<bool>(), "1".parse::<bool>().is_err());

    // A bool takes 1 byte, and match must cover both values.
    let label = match non_zero {
        true => "yes",
        false => "no",
    };
    println!("{} {}", std::mem::size_of::<bool>(), label);
}
Output
true true false
1 0
2
false true false
Some("adult") None
Ok(true) true
1 yes
  • Verdict: native. A condition must be a bool. as converts true to 1, but no cast goes from an integer to bool. & and | evaluate both operands. then_some and then turn a condition into an Option. "true".parse::<bool>() succeeds and "1" fails. A bool takes 1 byte, and a match on it must cover true and false.
  • Three-valued logic. SQL has TRUE, FALSE and UNKNOWN, and C# bool? follows the same rules: null & false is false and null | true is true, but null & true is null8.
  • Booleans as numbers. Counting the true values of a list is sum(flags) in Python and a filter and count in Rust. C, C++ and Python allow arithmetic on Booleans, and Java, C# and Go do not.
  • Option instead of a flag. A Boolean that says whether another value is valid is often better as an optional value, such as Option<T> in Rust. Rust bool::then_some turns a condition into an Option.
  • Bit sets. A set of flags fits in the bits of one integer, and &, | and ^ work on all flags at once.

Pitfalls

  • Truthiness that surprises. In Python, bool("False") is True because the string is not empty. In JavaScript, "0" and [] are truthy, but [] == false is true, because == converts both sides to numbers.
  • || for defaults. count || 10 in JavaScript gives 10 when count is 0. Use ??, which replaces only null and undefined.
  • Wrapper objects. A JavaScript new Boolean(false) is an object, so it is truthy. MDN says: "Do not use the Boolean() constructor with new"10. A Java Boolean can be null, and unboxing it in a condition throws NullPointerException.
  • Comparing with true. if (x == true) is longer than if (x), and in C it is wrong when x is a non-zero value other than 1.
  • Boolean parameters. A call such as copy(src, dst, true, false) does not say what the flags mean. Use named arguments, an enum or two functions.
  • & instead of &&. & evaluates both operands, so p != null & p.ok() in Java throws when p is null.

Cost

A Boolean operation is one machine instruction or less, and a condition compiles to a compare and a branch. A branch that the processor cannot predict costs more than the comparison itself, so code in a hot loop sometimes replaces a branch with arithmetic on the 0 or 1 of a Boolean. Storing Booleans as bytes uses eight times the memory of a bit set, which matters only for large arrays.

History

The Boolean type is named after George Boole, "who first defined an algebraic system of logic in the mid-19th century"1. ALGOL 60 was "One of the earliest programming languages to provide an explicit BOOLEAN data type"1. Its report defines the logical values as true and false and says that "The logical values have a fixed obvious meaning"11. According to Wikipedia, many later languages adopted this type, among them Simula 67 (1967), ALGOL 68 (1970), Pascal (1970), Ada (1980), Java (1995) and C# (2000)1.

FORTRAN at first had no logical values, and "FORTRAN IV (1962), however, follows the ALGOL 60 example by providing a Boolean data type (LOGICAL)"1. C used integers for decades: "Standard C (since C99) provides a Boolean type, called _Bool"1, and C23 made bool, true and false keywords. Python added bool in 2002 with PEP 285, which defined it as "a straightforward subtype (in C) of the int type"12, so old code that used 0 and 1 kept working.

References

  1. Boolean data type, Wikipedia, Introduction; ALGOL and the built-in BOOLEAN type; Fortran; C, C++, D, Objective-C, AWK
  2. The Java Language Specification, Java SE 25 Edition, Chapter 4, 4.2.5 The boolean Type and boolean Values
  3. The Go Programming Language Specification, Boolean types
  4. Built-in Types, Python documentation, Truth Value Testing; Boolean Type - bool
  5. Falsy, MDN Web Docs Glossary, Introduction
  6. Implicit conversions, C++ reference, cppreference.com, Boolean conversions
  7. Arithmetic types, C reference, cppreference.com, Boolean type
  8. bool, C# language reference, Introduction; Three-valued Boolean logic; Conversions
  9. Primitive Type bool, The Rust Standard Library, Description
  10. Boolean, MDN Web Docs, Boolean primitives and Boolean objects
  11. Revised Report on the Algorithmic Language ALGOL 60, 2.2.2 Logical values
  12. PEP 285, Adding a bool type, Abstract

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/JW76G0/text.yaml