fixup! Add another defer exercise

This commit is contained in:
Luka Markušić
2026-06-02 06:11:27 +02:00
parent e61bedaa25
commit bd55c4ac5a
5 changed files with 42 additions and 40 deletions

View File

@@ -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;
}

View File

@@ -1,18 +0,0 @@
//
// When there are multiple defers in a single block, they are executed in reverse order.
//
const std = @import("std");
pub fn main() void {
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;
// It might seem silly in this example, but it's important to know when
// deinitializing containers whose elements need to be deinitialized first.
}
std.debug.print("{d}\n", .{x});
}