Overhead at runtime with variable length arrays, but you will have to work hard enough to measure them. Note that sizeof(vla) not a compile-time constant if vla is a variable-length array.
The size of the array can be passed to the function at run time. If you decide to take the size from the command line argument and convert it to an integer and pass it to the function at run time, let it be so - it will work.
Variable-length arrays are used because the variables are automatically allocated to the correct size and automatically freed when they exit the function. This avoids over-allocation of space (allocating enough space for the largest possible size when you mostly work with the smallest size), and avoids problems with clearing the memory.
In addition, with multidimensional arrays, AFAIK behaves more like Fortran - you can dynamically tune all dimensions, rather than get stuck with fixed sizes for all but the leading dimension of the array.
Concrete evidence of some run-time overhead for VLAs — at least from GCC 4.4.2 to SPARC (Solaris 10).
Consider the two files below:
vla.c - using an array of variable length
#include <assert.h> #include <stddef.h> extern size_t identity_matrix(int n, int m); size_t identity_matrix(int n, int m) { int vla[n][m]; int i, j; assert(n > 0 && n <= 32); assert(m > 0 && m <= 32); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { vla[i][j] = 0; } vla[i][i] = 1; } return(sizeof(vla)); }
fla.c - using a fixed-length array
#include <assert.h> #include <stddef.h> extern size_t identity_matrix(int n, int m); size_t identity_matrix(int n, int m) { int fla[32][32]; int i, j; assert(n > 0 && n <= 32); assert(m > 0 && m <= 32); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { fla[i][j] = 0; } fla[i][i] = 1; } return(sizeof(fla)); }
Compilation and object file sizes
For comparison purposes, the names of the local array are different ( vla vs fla ), and the sizes in the array are different when they are declared - otherwise the files are the same.
I compiled using:
$ gcc -O2 -c -std=c99 fla.c vla.c
The size of the object file is slightly different - both "ls" and "size" are measured:
$ ls -l fla.o vla.o -rw-r--r-- 1 jleffler rd 1036 Jan 9 12:13 fla.o -rw-r--r-- 1 jleffler rd 1176 Jan 9 12:13 vla.o $ size fla.o vla.o fla.o: 530 + 0 + 0 = 530 vla.o: 670 + 0 + 0 = 670
I did not conduct detailed testing to find out how much overhead has been fixed and how many variables, but there is overhead when using VLA.