062_loop_expressions.zig 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. // With that in mind, see if you can fix the problem with this
  28. // program.
  29. //
  30. const print = @import("std").debug.print;
  31. pub fn main() void {
  32. const langs: [6][]const u8 = .{
  33. "Erlang",
  34. "Algol",
  35. "C",
  36. "OCaml",
  37. "Zig",
  38. "Prolog",
  39. };
  40. // Let's find the first language with a three-letter name and
  41. // return it from the for loop.
  42. const current_lang: ?[]const u8 = for (langs) |lang| {
  43. if (lang.len == 3) break lang;
  44. };
  45. if (current_lang) |cl| {
  46. print("Current language: {s}\n", .{cl});
  47. } else {
  48. print("Did not find a three-letter language name. :-(\n", .{});
  49. }
  50. }