Booleans

A boolean holds one of two values, true or false. Comparisons produce booleans, and if, while and the logical operators consume them.

The boolean types

TypeBitsBytesValues
bool881false, true
bool16162false, true
bool32324false, true
bool64648false, true

bool is a built-in alias of bool8, and the everyday spelling. The wider types hold the same two values in more storage; they exist to match the layout of foreign code, such as the four-byte BOOL of the Windows API, which is a bool32 in Rux. A compiler message names the canonical type, so a mistake with a bool reports bool8.

Reserved widths

bool128, bool256 and bool512 (16, 32 and 64 bytes) are named by the language but not implemented in rux 0.4.0. Using one is error: primitive type 'bool128' is reserved but is not implemented in this compiler version.

Associated constants

Imported from Core, each boolean type has Bits and Bytes (both uint): bool32::Bits is 32 and bool32::Bytes is 4.

Literals

true and false are the only boolean literals. Both are keywords, and their type is bool.

let ready = true;
let finished: bool = false;
let wide: bool32 = ready;

Operations

OperatorMeaning
!aNot
a && bAnd; b is evaluated only when a is true
a || bOr; b is evaluated only when a is false
a & bAnd, always evaluating both operands
a | bOr, always evaluating both operands
a ^ bExclusive or: true when exactly one operand is true
a == b, a != bEquality
let a = true;
let b = false;
let both = a && b;      // false
let either = a || b;    // true
let differ = a ^ b;     // true

&& binds more tightly than ||, so a || b && c is a || (b && c). See Logical for short-circuiting and Expressions for precedence.

Conditions

A condition must be a boolean. A number is not treated as one:

if 1 { … }
error: condition for 'if' must have type 'bool', but found 'int'

let flag = !5;
error: operator '!' requires a bool operand, but found 'int'

Write the comparison you mean, count != 0. Comparing a boolean with a literal, ready == true, is legal but says nothing ready does not.

Conversions

Every boolean width converts implicitly to every other, since all of them hold the same two values:

let flag: bool = true;
let wide: bool32 = flag;
let back: bool = wide;

Between booleans and other types, conversion is written with as:

ConversionResult
Boolean to an integer or float1 for true, 0 for false
Integer, float or character to a booleanfalse for zero, true for anything else
let one = true as int;          // 1
let zero = false as uint8;      // 0
let set = 256 as bool;          // true
let some = 0.5 as bool;         // true

A cast to a boolean tests the whole value for zero; it does not keep low bits. 256 as bool is true even though the low byte of 256 is zero, and the result reads back as exactly 1.

Without as, a number is never a boolean: let on: bool = 1; is error: cannot assign 'int' to 'bool8', and let n: int = true; is error: cannot assign 'bool8' to 'int'.

See also