C++ Logo


Advanced search

Re: [std-proposals] C++ never had a compiler without a stack

From: David Brown <david_at_[hidden]>
Date: Tue, 15 Aug 2023 17:34:32 +0200
On 15/08/2023 16:34, Lénárd Szolnoki via Std-Proposals wrote:
> On Tue, 2023-08-15 at 09:56 -0400, Julien Villemure-Fréchette via Std-
> Proposals wrote:
>> I think the intent of alloca in Posix and VLA in C was specifically
>> to have automatic cleanup semantics for objects with block scoped
>> lifetime. C++ already has the language feature that makes it possible
>> to ensure proper cleanup at end of scope, so the need for VLA
>> evaporates. If you look closely, the C language doesn't seem to make
>> any mention of the stack in the specification of VLAs, I think a pair
>> of malloc/free may be a possible implementation.
>> Neither C or C++ seem to formally require that implementation use a
>> stack for automatic allocations. alloca do mention a stack, but it is
>> specific to POSIX, not strictly standard C. IMO, If C had a
>> requirement that automatic allocations be done on a stack, then I
>> think alloca would be part of standard C, and VLAs would never have
>> existed
> One major difference between alloca and VLAs is that VLAs have the
> lifetime of the surrounding block, while alloca allocations are
> deallocated at the end of the function (not sure how that interacts
> with inlining).
> I do think that block scope VLAs had merit, it's just they really
> shouldn't have used the C array syntax.

They work just like non-variable local arrays, and have the same scope
and lifetime - using the syntax makes perfect sense.

  int xs[10];


  const int size = 10;
  int xs[size];

will generate identical code on any optimising C compiler, and you can
use "xs" in exactly the same way. But the first is a "normal" local
array, the second is a VLA. (In C++, the second is a normal local
array, and therefore valid even though C++ does not have VLA's.)

Having the same syntax seems natural to me.

> It's also worth mentioning that VLAs with lifetime that cross coroutine
> suspension points can't in general be allocated on the stack, neither
> in the coroutine frame. In general it would require an additional heap
> allocation, which could be optimised away in some special cases.

C++ does not have VLA's, and C does not have coroutines. But I could
well believe it could be a complication if a compiler supported both as
an extension.

> The last time I tried compilers don't implement VLAs that cross
> suspension points (even when VLAs are otherwise supported as a C++
> extension). I appreciate that this is probably very low priority.

Received on 2023-08-15 15:35:05