authorgravatar for twil3akine@gmail.comtwil3akine <twil3akine@gmail.com> 2026-05-10 01:34:16+09:00
committergravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2026-10-14 21:07:48+02:00
logfaef89cc6d74ebd75f82f95d55871a7282af8309
treee4f8f1e944c631ae9bde669a0b24a186db8d3bda
parenta6dddfa8a07c3fffd89a76691d1a2c00319fd20f
signature Signed by SSH key SHA256:7B/LJ7bpR1eX8aCXSr4mtd5M45VMPKcx9zY8e95b5QM

langref: clarify for else example


1 files changed, 14 insertions(+), 12 deletions(-)

doc/langref/test_for.zig+14-12
...@@ -75,20 +75,22 @@ test "for reference" {...@@ -75,20 +75,22 @@ test "for reference" {
7575
76test "for else" {76test "for else" {
77 // For allows an else attached to it, the same as a while loop.77 // For allows an else attached to it, the same as a while loop.
78 const items = [_]?i32{ 3, 4, null, 5 };78 // The else branch is evaluated when the loop completes without a break.
79 const items = [_]i32{ 3, 4, 5 };
7980
80 // For loops can also be used as expressions.
81 // Similar to while loops, when you break from a for loop, the else branch is not evaluated.
82 var sum: i32 = 0;
83 const result = for (items) |value| {81 const result = for (items) |value| {
84 if (value != null) {82 if (value > 10) break value;
85 sum += value.?;83 } else 0;
86 }84
87 } else blk: {85 try expectEqual(0, result);
88 try expectEqual(12, sum);86
89 break :blk sum;87 const more_items = [_]i32{ 3, 4, 11, 5 };
90 };88
91 try expectEqual(12, result);89 const another_result = for (more_items) |value| {
90 if (value > 10) break value;
91 } else 0;
92
93 try expectEqual(11, another_result);
92}94}
9395
94// test96// test