Remix.run Logo
eikenberry 7 months ago

Is there a language that makes this explicit, allocates the variables on the stack via compiler enforced notation?

fanf2 7 months ago | parent | next [-]

C, C++, Rust, Zig, …

im3w1l 7 months ago | parent | next [-]

I'm not sure about Zig, but what strikes me about the others are that they change the type of the object.

T vs T*.

It would be kind of neat if you could have an annotation on the variable instead that didn't change the type.

You could in C++ make a reference T& which is almost that - references behave identically to the real thing. But I think freeing the memory backing a reference is probably quite questionable?

eikenberry 7 months ago | parent | prev [-]

What's Zig's notation for it?

masklinn 7 months ago | parent [-]

Not doing anything, same as the other 3.

Heap allocation is what requires requesting memory from an allocator.

eikenberry 7 months ago | parent [-]

Right.. been using GC languages to long. Everything allocated to the stack unless it is specifically allocated to the heap. I was stuck thinking about what the keywords were. But I'm still curious.. are there any GC languages that have a way to specify if something should go on the stack or the heap?

masklinn 7 months ago | parent | next [-]

> are there any GC languages that have a way to specify if something should go on the stack or the heap?

I think only in the sense that some GCd language have value (stack) types as a separate hierarchy from heap types? E.g. structs in C# or Swift are stack-allocated (and value-identity, and copied) whereas classes are heap-allocated.

Adding that for java is one of the goals of Project Valhalla I believe.

stassats 7 months ago | parent | prev [-]

Common Lisp. The dynamic-extent declaration allows for stack allocation.

neonsunset 7 months ago | parent | prev [-]

C# (.NET in general) :)

Well, variables cannot be forced to stack specifically. They are placed in the "local scope". And that would usually be either stack or CPU registers - thinking in stack only is a somewhat flawed mental model.

Both C# and F# complicate this by supporting closures, iterator and async methods which capture variables placing them in a state machine box / display class instead which would be located on the heap, unless stack-allocated by escape analysis (unlikely because these usually cross method boundaries).

However, .NET has `ref structs` (or, in F#, [<Struct; IsByRefLike>] types) which are subject to lifetime analysis and can never be placed on the heap directly or otherwise.