Inserted ex. 32 unreachable, added quiz4.

This commit is contained in:
Dave Gauer 2021-02-03 19:19:31 -05:00
parent cd80aeb190
commit 738a9f6cda
5 changed files with 68 additions and 5 deletions

38
32_unreachable.zig Normal file
View file

@ -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", .{});
}

24
34_quiz4.zig Normal file
View file

@ -0,0 +1,24 @@
//
// Quiz time. See if you can make this program work!
//
// Solve this any way you like, just be sure the output is:
//
// my_num=42
//
const std = @import("std");
const NumError = error{ IllegalNumber };
pub fn main() void {
const stdout = std.io.getStdOut().writer();
const my_num: u32 = getNumber();
try stdout.print("my_num={}\n", .{my_num});
}
// Just don't modify this function. It's "perfect" the way it is. :-)
fn getNumber() NumError!u32 {
if( false ) return NumError.IllegalNumber;
return 42;
}

View file

@ -66,10 +66,10 @@ Planned exercises:
* [x] While
* [x] For
* [x] Functions
* [x] Errors
* [x] Defer
* [x] Errors (error/try/catch/if-else-err)
* [x] Defer (and errdefer)
* [x] Switch
* [ ] Unreachable
* [x] Unreachable
* [ ] Pointers
* [ ] Pointer sized integers
* [ ] Multi pointers

View file

@ -99,8 +99,9 @@ check_it 28_defer2.zig "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done."
check_it 29_errdefer.zig "Getting number...got 5. Getting number...failed!"
check_it 30_switch.zig "ZIG?"
check_it 31_switch2.zig "ZIG!"
check_it 32_iferror.zig "2<4. 3<4. 4=4. 5>4. 6>4." "Seriously, what's the deal with fours?"
#check_it 33_quiz4.zig "foo" "Can you make this work?"
check_it 32_unreachable.zig "1 2 3 9 8 7"
check_it 33_iferror.zig "2<4. 3<4. 4=4. 5>4. 6>4." "Seriously, what's the deal with fours?"
check_it 34_quiz4.zig "my_num=42" "Can you make this work?"
echo
echo " __ __ _ "