diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index ddfd066e65..2c5fe7e02c 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -1243,7 +1243,8 @@ fn (mut g Gen) stmt(node ast.Stmt) { } fn (mut g Gen) write_defer_stmts() { - for defer_stmt in g.defer_stmts { + for i := g.defer_stmts.len - 1; i >= 0; i-- { + defer_stmt := g.defer_stmts[i] g.writeln('// Defer begin') g.writeln('if (${g.defer_flag_var(defer_stmt)} == true) {') g.indent++ diff --git a/vlib/v/tests/defer_test.v b/vlib/v/tests/defer_test.v index d01e6b7b39..8cdc73db84 100644 --- a/vlib/v/tests/defer_test.v +++ b/vlib/v/tests/defer_test.v @@ -101,3 +101,19 @@ fn test_defer_with_if() { set_num_if(mut n, 20, false) assert n.val == 10 } + +fn test_defer_order() { + mut i := 0 + defer { + i++ + assert i == 3 + } + defer { + i++ + assert i == 2 + } + defer { + i++ + assert i == 1 + } +}