062_loop_expressions.zig 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. //
  2. // Remember using if/else statements as expressions like this?
  3. //
  4. // var foo: u8 = if (true) 5 else 0;
  5. //
  6. // Zig also lets you use for and while loops as expressions.
  7. //
  8. // Like 'return' for functions, you can return a value from a
  9. // loop block with break:
  10. //
  11. // break true; // return boolean value from block
  12. //
  13. // But what value is returned from a loop if a break statement is
  14. // never reached? We need a default expression. Thankfully, Zig
  15. // loops also have 'else' clauses! As you might have guessed, the
  16. // else clause is evaluated once a while condition becomes false
  17. // or a for loop runs out of items.
  18. //
  19. // const two: u8 = while (true) break 2 else 0; // 2
  20. // const three: u8 = for ([1]u8{1}) |f| break 3 else 0; // 3
  21. //
  22. // If you do not provide an else clause, an empty one will be
  23. // provided for you, which will evaluate to the void type, which
  24. // is probably not what you want. So consider the else clause
  25. // essential when using loops as expressions.
  26. //
  27. // const four: u8 = while (true) {
  28. // break 4;
  29. // }; // <-- ERROR! Implicit 'else void' here!
  30. //
  31. // With that in mind, see if you can fix the problem with this
  32. // program.
  33. //
  34. const print = @import("std").debug.print;
  35. pub fn main() void {
  36. const langs: [6][]const u8 = .{
  37. "Erlang",
  38. "Algol",
  39. "C",
  40. "OCaml",
  41. "Zig",
  42. "Prolog",
  43. };
  44. // Let's find the first language with a three-letter name and
  45. // return it from the for loop.
  46. const current_lang: ?[]const u8 = for (langs) |lang| {
  47. if (lang.len == 3) break lang;
  48. };
  49. if (current_lang) |cl| {
  50. print("Current language: {s}\n", .{cl});
  51. } else {
  52. print("Did not find a three-letter language name. :-(\n", .{});
  53. }
  54. }