032_unreachable.zig 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // Zig has an "unreachable" statement. Use it when you want to tell the
  3. // compiler that a branch of code should never be executed and that the
  4. // mere act of reaching it is an error.
  5. //
  6. // if (true) {
  7. // ...
  8. // } else {
  9. // unreachable;
  10. // }
  11. //
  12. // Here we've made a little virtual machine that performs mathematical
  13. // operations on a single numeric value. It looks great but there's one
  14. // little problem: the switch statement doesn't cover every possible
  15. // value of a u8 number!
  16. //
  17. // WE know there are only three operations but Zig doesn't. Use the
  18. // unreachable statement to make the switch complete. Or ELSE. :-)
  19. //
  20. const std = @import("std");
  21. pub fn main() void{
  22. const operations = [_]u8{ 1, 1, 1, 3, 2, 2 };
  23. var current_value: u32 = 0;
  24. for(operations) |op|{
  25. switch(op){
  26. 1 => {
  27. current_value += 1;
  28. },
  29. 2 => {
  30. current_value -= 1;
  31. },
  32. 3 => {
  33. current_value *= current_value;
  34. },
  35. else => { unreachable; },
  36. }
  37. std.debug.print("{} ", .{current_value});
  38. }
  39. std.debug.print("\n", .{});
  40. }