The C Standard allows C compilers to support variable length arrays. The const qualifier for a variable used as an array size does not make a constant integer expression in C opposite to C++.
From the C Standard (6.6 Constant expressions)
6 An integer constant expression117) shall have integer type and shall
only have operands that are integer constants, enumeration constants,
character constants, sizeof expressions whose results are integer
constants, and floating constants that are the immediate operands of
casts. Cast operators in an integer constant expression shall only
convert arithmetic types to integer types, except as part of an
operand to the sizeof operator.
The word integer or character constants in this quote means literals.
As for variable length arrays then ( The C Standard 6.7.6.2 Array declarators)
4 If the size is not present, the array type is an incomplete type. If
the size is * instead of being an expression, the array type is a
variable length array type of unspecified size, which can only be used
in declarations or type names with function prototype scope; such
arrays are nonetheless complete types. If the size is an integer
constant expression and the element type has a known constant size,
the array type is not a variable length array type; otherwise, the
array type is a variable length array type. (Variable length arrays
are a conditional feature that implementations need not support; see
6.10.8.3.)
Some C++ compilers can have their own language extensions that allow also to use variable length arrays in a C++ program. But it is not a X++ Standard feature.
Even if a C++ compiler supports variable length arrays it is better to use the standard class template std::vector
instead of variable length arrays.
Pay attention to that you may not initialize a variable length arrays in C when they are declared. And variable length arrays have the automatic storage duration. You may apply the sizeof
operator to variable length arrays that is evaluated at run-time.
Here is a demonstrative program of using variable length arrays.
#include <stdio.h>
void f( size_t, size_t, int[][*] );
void f( size_t m, size_t n, int a[][n] )
{
for ( size_t i = 0; i < m; i++ )
{
for ( size_t j = 0; j < n; j++ )
{
a[i][j] = n * i + j;
}
}
}
void g( size_t, size_t, int[][*] );
void g( size_t m, size_t n, int a[][n] )
{
for ( size_t i = 0; i < m; i++ )
{
for ( size_t j = 0; j < n; j++ )
{
printf( "%2d ", a[i][j] );
}
putchar( '\n' );
}
}
int main(void)
{
const size_t m1 = 3, n1 = 3;
int a[m1][n1];
f( m1, n1, a );
g( m1, n1, a );
putchar( '\n' );
const size_t m2 = 4, n2 = 5;
int b[m2][n2];
f( m2, n2, b );
g( m2, n2, b );
putchar( '\n' );
return 0;
}
The program output is
0 1 2
3 4 5
6 7 8
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19