diff options
| author | Chris Boesch <chrboesch@noreply.codeberg.org> | 2026-06-02 08:56:50 +0200 |
|---|---|---|
| committer | Chris Boesch <chrboesch@noreply.codeberg.org> | 2026-06-02 08:56:50 +0200 |
| commit | f6dda8181a28cc5bbb343900bec7d8157f51536e (patch) | |
| tree | b5dae98c4dacbcc5046bddebd5488938894a9210 /exercises/028_defer2.zig | |
| parent | ac9f96459ce1ce2c1cec5605cf6075d0fbf559b7 (diff) | |
| parent | bd55c4ac5a235778f78b91c37a0bf1516bfbcc55 (diff) | |
Merge pull request 'Add another defer exercise' (#438) from mark2185/exercises:defer3 into main
Reviewed-on: https://codeberg.org/ziglings/exercises/pulls/438
Diffstat (limited to 'exercises/028_defer2.zig')
| -rw-r--r-- | exercises/028_defer2.zig | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/exercises/028_defer2.zig b/exercises/028_defer2.zig index 35c1326..b490a89 100644 --- a/exercises/028_defer2.zig +++ b/exercises/028_defer2.zig @@ -10,6 +10,8 @@ pub fn main() void { for (animals) |a| printAnimal(a); std.debug.print("done.\n", .{}); + + std.debug.print("Answer to everything? {d}\n", .{calculateTheUltimateQuestionOfLife()}); } // This function is _supposed_ to print an animal name in parentheses @@ -35,3 +37,24 @@ fn printAnimal(animal: u8) void { std.debug.print("Unknown", .{}); } + +// This function is supposed to calculate the answer to the +// ultimate question of life, the universe, and everything, +// but it needs to be deferred as far in the future as possible, +// in order to gather more data. +// +// When there are multiple defers in a single block, they are executed in reverse order. +// This example might seem silly, but it's important to know when e.g. +// deinitializing containers whose elements need to be deinitialized first. +fn calculateTheUltimateQuestionOfLife() u32 { + var x: u32 = 100; + + // Try reordering the statements to get the answer 42 + { + defer x = x / 10; + defer x = x + 11; + defer x = x * 2; + } + + return x; +} |
