Boolean Literals
Boolean literals are the two built-in logical values:
truefalse
They have type bool (types).
Notes#
What works end-to-end today (lexer → parser → checker → lowering → codegen):
true/falseliteral tokens.boolvariables, parameters, and return values.if/whileconditions must have typebool.- Boolean operators:
- unary
!, - short-circuit
&&and||(left-to-right, skip evaluation of the right operand when the result is already determined).
Examples#
Basic control flow#
fn main () -> int {
let ready: bool = true;
if ready {
return 0;
} else {
return 1;
}
}
Short-circuit evaluation#
fn returns_false () -> bool {
return false;
}
fn main () -> int {
// Because the left operand is `true`, the right operand is evaluated.
let a: bool = true && returns_false();
if a {
return 1;
}
// Because the left operand is `false`, the right operand is not evaluated.
let b: bool = false && returns_false();
if b {
return 2;
}
return 0;
}
Common Pitfalls#
- Assuming “truthy” values:
boolis a distinct type. Use comparisons to produce abool(for examplex != 0) rather than writingif x { ... }. - Forgetting short-circuiting:
&&and||may skip evaluating the right operand; do not rely on side effects in the skipped operand.
Related Documents#
- types (the
booltype) - operators (
!,&&,||) - flow if else (
ifstatement semantics) - flow while (
whilestatement semantics)
Source repository · Edit this page · View Markdown