@@ -181,15 +181,24 @@ fn (mut g Gen) needs_conds_order(node ast.IfExpr) bool {
181181}
182182
183183fn (mut g Gen) if_expr (node ast.IfExpr) {
184+ use_outer_tmp := g.outer_tmp_var != ''
185+ saved_outer_tmp_var := g.outer_tmp_var
186+ if use_outer_tmp {
187+ g.outer_tmp_var = ''
188+ }
189+
184190 // For simple if expressions we can use C's `?:`
185191 // `if x > 0 { 1 } else { 2 }` => `(x > 0)? (1) : (2)`
186192 // For if expressions with multiple statements or another if expression inside, it's much
187193 // easier to use a temp var, than do C tricks with commas, introduce special vars etc
188194 // (as it used to be done).
189195 // Always use this in -autofree, since ?: can have tmp expressions that have to be freed.
190- needs_tmp_var := g.inside_if_option || g.need_tmp_var_in_if (node)
196+ needs_tmp_var := g.inside_if_option || g.need_tmp_var_in_if (node) || use_outer_tmp
191197 needs_conds_order := g.needs_conds_order (node)
192- tmp := if g.inside_if_option || (node.typ != ast.void_type && needs_tmp_var) {
198+ tmp := if use_outer_tmp {
199+ // Use the tmp var from outer context (e.g. from stmts_with_tmp_var)
200+ saved_outer_tmp_var
201+ } else if g.inside_if_option || (node.typ != ast.void_type && needs_tmp_var) {
193202 g.new_tmp_var ()
194203 } else {
195204 ''
@@ -267,7 +276,8 @@ fn (mut g Gen) if_expr(node ast.IfExpr) {
267276 }
268277 cur_line = g.go_before_last_stmt ()
269278 g.empty_line = true
270- if tmp != '' {
279+ if tmp != '' && ! use_outer_tmp {
280+ // Only declare the tmp var if it's not from outer context
271281 if node.typ == ast.void_type && g.last_if_option_type != 0 {
272282 // nested if on return stmt
273283 g.write2 (g.styp (g.unwrap_generic (g.last_if_option_type)), ' ' )
0 commit comments