aboutsummaryrefslogtreecommitdiff
path: root/32_unreachable.zig
diff options
context:
space:
mode:
authorDave Gauer <dave@ratfactor.com>2021-02-03 19:19:31 -0500
committerDave Gauer <dave@ratfactor.com>2021-02-03 19:19:31 -0500
commit738a9f6cda62f3570e44dc93f8e200afc2cc1b51 (patch)
tree0f690aeaee95d317d80ee3913b0fb0b6245b1edb /32_unreachable.zig
parentcd80aeb19061b9d222d24cdb4d0764a210536531 (diff)
downloadziglings-738a9f6cda62f3570e44dc93f8e200afc2cc1b51.tar.gz
ziglings-738a9f6cda62f3570e44dc93f8e200afc2cc1b51.tar.bz2
ziglings-738a9f6cda62f3570e44dc93f8e200afc2cc1b51.tar.xz
ziglings-738a9f6cda62f3570e44dc93f8e200afc2cc1b51.zip
Inserted ex. 32 unreachable, added quiz4.
Diffstat (limited to '32_unreachable.zig')
-rw-r--r--32_unreachable.zig38
1 files changed, 38 insertions, 0 deletions
diff --git a/32_unreachable.zig b/32_unreachable.zig
new file mode 100644
index 0000000..c81efac
--- /dev/null
+++ b/32_unreachable.zig
@@ -0,0 +1,38 @@
+//
+// Zig has an "unreachable" statement. Use it when you want to tell the
+// compiler that a branch of code should never be executed and that the
+// mere act of reaching it is an error.
+//
+// if (true) {
+// ...
+// } else {
+// unreachable;
+// }
+//
+// Here we've made a little virtual machine that performs mathematical
+// operations on a single numeric value. It looks great but there's one
+// little problem: the switch statement doesn't cover every possible
+// value of a u8 number!
+//
+// WE know there are only three operations but Zig doesn't. Use the
+// unreachable statement to make the switch complete. Or ELSE. :-)
+//
+const std = @import("std");
+
+pub fn main() void {
+ const operations = [_]u8{ 1, 1, 1, 3, 2, 2 };
+
+ var current_value: u32 = 0;
+
+ for (operations) |op| {
+ switch (op) {
+ 1 => { current_value += 1; },
+ 2 => { current_value -= 1; },
+ 3 => { current_value *= current_value; },
+ }
+
+ std.debug.print("{} ", .{current_value});
+ }
+
+ std.debug.print("\n", .{});
+}