From e82c96f6f86ca448ecc1dc0ee0e16dfd3375c915 Mon Sep 17 00:00:00 2001 From: Heman Gandhi Date: Wed, 3 Jan 2024 10:37:59 +0900 Subject: [PATCH 1/2] Add a section on booleans --- chapter-1.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/chapter-1.md b/chapter-1.md index 76392c28..a3ff50f1 100644 --- a/chapter-1.md +++ b/chapter-1.md @@ -767,6 +767,32 @@ const Tagged = union(enum) { a: u8, b: f32, c: bool }; const Tagged2 = union(enum) { a: u8, b: f32, c: bool, none }; ``` +# Boolean Rules + +Zig uses the type `bool` for booleans with two values: `true` and `false`. + +Logical ands and ors use the `and` and `or` keywords respectively. +These operations short-circut. + +Note: logical negation is expressed with `!` (not a keyword). +Furthermore, bitwise operators cannot be used with booleans. + +``` +test "boolean and and or with short circuits" { + const t = true; + const f = !t; + try expect(t or f); + try expect(t and !f); + + // Optionals are coverd in more detail later. + // Just know that in this case optional_to_induce_error.? is a runtime error. + const optional_to_induce_error: ?bool = null; + // None of the below cause an error thanks to short-circuiting. + try expect(t or optional_to_induce_error.?); + try expect(!(f and optional_to_induce_error.?)); +} +``` + # Integer Rules Zig supports hex, octal and binary integer literals. From eb7aad20071d05d111a9922706a02a113fcceb01 Mon Sep 17 00:00:00 2001 From: Heman Gandhi Date: Wed, 3 Jan 2024 10:47:52 +0900 Subject: [PATCH 2/2] Fix spelling --- chapter-1.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapter-1.md b/chapter-1.md index a3ff50f1..630102ac 100644 --- a/chapter-1.md +++ b/chapter-1.md @@ -784,7 +784,7 @@ test "boolean and and or with short circuits" { try expect(t or f); try expect(t and !f); - // Optionals are coverd in more detail later. + // Optionals are covered in more detail later. // Just know that in this case optional_to_induce_error.? is a runtime error. const optional_to_induce_error: ?bool = null; // None of the below cause an error thanks to short-circuiting.