#Avoid creating local scope for statements that get compiled to what could be scopeless?

1 messages · Page 1 of 1 (latest)

open pewter
#

for example:

if (is_true) {
a();
} else {
b();
}

where 'is_true' is comptime known.

This should compile to a() or b(), and I would like to avoid creating a new scope in the situation that the blocks contain a defer or errdefer for example.

cloud nacelle
#

AFAIK this is simply how the compiler works. if you want to be sure do a if(comptime is_true). It won't even analyse the dead code path.

#

Ah though to clarify - it's specifically the scope you're trying to avoid? I may have misunderstood. In which case
if (is_true) a() else b(); should do

dim jolt
#

whats this about defer and errdefer?

violet portal
#

Maybe a defer block would suit

defer {
    if (is_true) {
        ...
    } else {
        ...
    }
}
sand pilot
#

you cant avoid the creation of a scope.
i think i know what you want regarding defer but i am struggling to make an example without a more useful snippet of your code.

open pewter
#

For example, what is the correct way to conditionally do something and errdefer/defer its cleanup when the condition is comptime known?

#

eg


if (is_true) {
  const m = try allocator.alloc(...);
  defer allocator.free(m);
}
#

So far what I have done is something like:

if (is_true) m = try allocator.alloc(...);
defer if (is_true) allocator.free(m);
vague otter
#

No way to hoist defers or declarations

#

The way you're doing it is more or less how you'd it

#

You can have a decl that's conditionally one type or another depending on the comptime condition

#

ie const m = if (cond) try gpa.alloc(...) else {}; to make m just be a void when !cond (note: can omit the else {}, since the else branch defaults to void