030_switch.zig 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // The "switch" statement lets you match the possible values of an
  3. // expression and perform a different action for each.
  4. //
  5. // This switch:
  6. //
  7. // switch (players) {
  8. // 1 => startOnePlayerGame(),
  9. // 2 => startTwoPlayerGame(),
  10. // else => {
  11. // alert();
  12. // return GameError.TooManyPlayers;
  13. // }
  14. // }
  15. //
  16. // Is equivalent to this if/else:
  17. //
  18. // if (players == 1) startOnePlayerGame();
  19. // else if (players == 2) startTwoPlayerGame();
  20. // else {
  21. // alert();
  22. // return GameError.TooManyPlayers;
  23. // }
  24. //
  25. const std = @import("std");
  26. pub fn main() void {
  27. const lang_chars = [_]u8{ 26, 9, 7, 42 };
  28. for (lang_chars) |c| {
  29. switch (c) {
  30. 1 => std.debug.print("A", .{}),
  31. 2 => std.debug.print("B", .{}),
  32. 3 => std.debug.print("C", .{}),
  33. 4 => std.debug.print("D", .{}),
  34. 5 => std.debug.print("E", .{}),
  35. 6 => std.debug.print("F", .{}),
  36. 7 => std.debug.print("G", .{}),
  37. 8 => std.debug.print("H", .{}),
  38. 9 => std.debug.print("I", .{}),
  39. 10 => std.debug.print("J", .{}),
  40. // ... we don't need everything in between ...
  41. 25 => std.debug.print("Y", .{}),
  42. 26 => std.debug.print("Z", .{}),
  43. // Switch statements must be "exhaustive" (there must be a
  44. // match for every possible value). Please add an "else"
  45. // to this switch to print a question mark "?" when c is
  46. // not one of the existing matches.
  47. }
  48. }
  49. std.debug.print("\n", .{});
  50. }