On 02.02.2017 17:32, Bonita Montero wrote:
> Am 02.02.2017 um 03:09 schrieb Paul:
>
>> void makeArray(const int K)
>> {
>> int a[K];
>> }
>
> That's not legal C++-code.
>
> But you can use alloca in C++ to have a variable length array:
>
> #include <malloc.h>
>
> void makeArray( const int K )
> {
> int *a = (int *)alloca( K * sizeof(int) );
> }
Note that
• `alloca` is not standard, but is commonly available, and
• unfortunately how to check for allocation failure, or even if that's
possible at all, differs between compilers/systems.
There have been proposals for variable length arrays in C++, but as far
as I know they've all been discontinued. :( E.g. see <url:
http://stackoverflow.com/a/40656359/464581>.
It's sad because it absolutely needs core language support: one can't
implement a reasonable dynamic length stack based array as a library
solution. One IMO unreasonable way, that in principle could be used for
e.g. string encoding conversions, is to allocate a global buffer that is
treated as a stack and passed down the call chain. This was suggested
seriously in comp.std.c++ when VLA were discussed there, but I have
never seen or heard about that possible technique elsewhere.
> With almost any copiler you lose one register which becomes the frame
> -pointer because the stack-pointer is advanced a variable distance and
> the compiler would not be able to find back to the calling stack-frame
> without this frme-pointer.
In a debug build there's usually a frame pointer regardless of whether
`alloca` is used or not. This allows a debugger to walk up the stack in
order to present the current call chain. A modern processor has enough
registers that I wouldn't worry about any lost optimization opportunity.
The main problem, as I see it, apart from the low level of abstraction,
is for portable code: that because `alloca` isn't standard, there's no
directly portable way to check if it succeeds.
For portable code one would have to write a failure-checking wrapper
with slightly different implementations for different systems, and I'm
not sure if all implementations of `alloca` support such checking. As an
example of failure checking, Microsoft's `alloca` reports failure via an
SEH exception, which is not a C++ exception. One needs to use Windows
specific language extensions to catch that.