mirror of
https://codeberg.org/ziglings/exercises.git
synced 2026-06-08 07:50:00 +00:00
Add another defer exercise
This commit is contained in:
18
exercises/116_defer3.zig
Normal file
18
exercises/116_defer3.zig
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
//
|
||||||
|
// 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});
|
||||||
|
}
|
||||||
14
patches/patches/116_defer3.patch
Normal file
14
patches/patches/116_defer3.patch
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
--- exercises/116_defer3.zig 2026-05-31 22:29:56.189323732 +0200
|
||||||
|
+++ answers/116_defer3.zig 2026-05-31 22:30:17.749186667 +0200
|
||||||
|
@@ -7,9 +7,9 @@
|
||||||
|
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;
|
||||||
|
+ defer x = x + 11;
|
||||||
|
+ defer x = x / 10;
|
||||||
|
|
||||||
|
// It might seem silly in this example, but it's important to know when
|
||||||
|
// deinitializing containers whose elements need to be deinitialized first.
|
||||||
@@ -1223,6 +1223,10 @@ const exercises = [_]Exercise{
|
|||||||
.main_file = "115_packed2.zig",
|
.main_file = "115_packed2.zig",
|
||||||
.output = "",
|
.output = "",
|
||||||
},
|
},
|
||||||
|
.{
|
||||||
|
.main_file = "116_defer3.zig",
|
||||||
|
.output = "42",
|
||||||
|
},
|
||||||
.{
|
.{
|
||||||
.main_file = "999_the_end.zig",
|
.main_file = "999_the_end.zig",
|
||||||
.output =
|
.output =
|
||||||
|
|||||||
Reference in New Issue
Block a user