diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index bdc860d612..11e0806359 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -917,13 +917,11 @@ fn (mut g Gen) stmts_with_tmp_var(stmts []ast.Stmt, tmp_var string) { g.stmt_path_pos << g.out.len g.skip_stmt_pos = true if stmt is ast.ExprStmt { - sym := g.table.get_type_symbol(stmt.typ) - if sym.name in ['Option2', 'Option'] || stmt.expr is ast.None { - tmp := g.new_tmp_var() - g.write('Option $tmp = (Option){.state = 0,.err = ') + if stmt.typ == table.error_type_idx || stmt.expr is ast.None { + g.writeln('${tmp_var}.state = 2;') + g.write('${tmp_var}.err = ') g.expr(stmt.expr) - g.writeln('};') - g.writeln('memcpy(&$tmp_var, &$tmp, sizeof(Option));') + g.writeln(';') } else { mut styp := g.base_type(stmt.typ) $if tinyc && x32 && windows { diff --git a/vlib/v/tests/if_expr_of_optional_test.v b/vlib/v/tests/if_expr_of_optional_test.v index 928a25b424..dad9b36d5c 100644 --- a/vlib/v/tests/if_expr_of_optional_test.v +++ b/vlib/v/tests/if_expr_of_optional_test.v @@ -7,6 +7,10 @@ fn foo2() ?int { } fn foo3() ?int { + return if false { 1 } else { error('foo3 error') } +} + +fn foo4() ?int { return if true { 2 } else { 0 } } @@ -19,9 +23,15 @@ fn test_if_expr_of_optional() { println(a2) assert a2 == 1 - a3 := foo3() or { panic('error') } - println(a3) - assert a3 == 2 + if _ := foo3() { + assert false + } else { + assert err.msg == 'foo3 error' + } + + a4 := foo4() or { panic('error') } + println(a4) + assert a4 == 2 } fn foo_complex() ?int {