This question arose from a remark Eric Postpischil made in another thread.
I have a hard time understanding the use of variable length arrays (VLAs) as function parameters:
- The array size is not checked.
- The array size is not recoverable from the array because the standard type adjustment array -> pointer applies for VLAs as well, as the
sizeof()
calls below demonstrate; even though it would be perfectly possible to pass the whole array on the stack, just as VLAs are created on the stack when they are defined. - The size must be passed as an additional parameter, as with pointers.
So why does the language permit to declare function with VLA parameters if they do not offer any advantage and are adjusted like any other array argument to a pointer? Why is the size expression evaluated if it is not used by the language (e.g. to check the size of the actual argument) and is not obtainable inside the function (one still has to pass an explicit variable for that)??
In order to make clearer what I'm baffled about consider the following program (live example here). All function declarations are apparently equivalent. But as Eric pointed out in the other thread, the parameter size expression in the function's declaration is evaluated at run time. The size expression is not ignored.
It is unclear to me what benefit that would have because the size and its evaluation has no effect (beyond possible side effects). In particular, to repeat myself, that information cannot be used by code inside the function. The most obvious change would have been to pass VLAs on the stack like structures. They are, after all, usually also on the stack on the caller side. But like with arrays of constant length the type is adjusted already at declaration time to a pointer — all declarations below are equivalent. Nonetheless the useless and discarded array size expression is evaluated.
#include <stdio.h>// Nothing to see here.extern void ptr(int *arr);// Identical to the above.extern void ptr(int arr[]);// Still identical. Is 1 evaluated? Who knows ;-).extern void ptr(int arr[1]);// Is printf evaluated when called? Yes.// But the array is still adjusted to a pointer.void ptr(int arr[printf("Call-time evaluation of size parameter\n")]){}// This would not compile, so the declarations above must be equivalent.// extern void ptr(int **p);int main(){ ptr(0); ptr(0); return 0;}