It is extremely efficient because it is a construct that leads to a compile-time constant (except for VLAs C99, see below). You can use:
sizeof(array)/sizeof(array[0])
. , (, ).
: VLA C99, :
- , ; , . (6.5.3.4/2)
VLA ( ), VLA . VLA . :
#include <stdio.h>
#define countof_array(arr) (sizeof(arr)/sizeof(arr[0]))
int vlaSize(void)
{
return 8;
}
int main(void)
{
int fixed_array[9] = { 1,2,3,4,5,6,7,8,9 };
int vla_array[vlaSize()];
printf("Fixed array: size = %zu bytes, count = %zu elements\n",
sizeof(fixed_array), countof_array(fixed_array));
printf("VLA array: size = %zu bytes, count = %zu elements\n",
sizeof(vla_array), countof_array(vla_array));
return 0;
}
:
$ gcc -Wall -std=c99 so-misc.c
$ ./a.out
Fixed array: size = 36 bytes, count = 9 elements
VLA array: size = 32 bytes, count = 8 elements
, :
. , countof_array VLA [...]
, , , . .
, - , VLA , VLA. , VLA, - .