Why does variable length array not work on a global scale?

If I write an array of variable length as local, for example:

#include <stdio.h>

int main()
{
    int i=1;
    int a[i];
    printf("%zu",sizeof(a));
}

It works great in the GCC compiler.

But, if I write an array of variable length as globally, for example:

#include <stdio.h>
int i=1;
int a[i];
int main()
{
    printf("%zu",sizeof(a));
}

The GCC compiler then produces the following error:

prog.c:4:5: error: variably modified 'a' at file scope
  int a[i];
+4
source share
4 answers

From standard 6.7.6.2

If the identifier is declared as an object with a static or storage time stream, it should not have an array type of variable length.

+15
source

This is not allowed, because if it is not limited to the extreme, it can be extremely error prone. Consider this:

extern const int sz; // Another TU
int a[sz];

sz ( ). 0 ( ). .

, TU, :

const int sz = 10;
int a[sz];

VLA ? 10.

. , , . ., , .

+4

, , , , .

-, : ( C11, §6.2.4/P2)

- , . , , 33) .34)

: ( P3)

, _Thread_local, , specifier static, . - , , .

, : ( §6.2.3/P5)

[...] , .

, a .

, , VLA , / ( , ), , .

C11 6.7.6.2, .

[...] , .

+4

. ; , , , main(). , , , .

VLA - . , , . , , , , , malloc().

+4

Source: https://habr.com/ru/post/1690766/


All Articles