0
#include <stdio.h>

const int i=1;
int a[i];

int main()
{
    printf("Hello World");

    return 0;
}

Size of an array must be a constant expression. I have declared i to be const, why still the error?

main.c:12:5: error: variably modified 'a' at file scope
 int a[i];
     ^

Why does moving the part inside the function main work:

#include <stdio.h>

int main()
{
    const int i=1;
    int a[i];
    printf("Hello World");

    return 0;
}

Thanks.

  • also: https://stackoverflow.com/questions/18848537/can-a-const-variable-be-used-to-declare-the-size-of-an-array-in-c – Jean-François Fabre Sep 16 '17 at 12:20
  • here you can define a VLA locally, it isn't a problem for your compiler. But statically it's not possible: size must be known at compile time. – Jean-François Fabre Sep 16 '17 at 12:21
  • 1
    C11 draft standard n1570, *6.7.6.2 Array declarators 2 If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.* – EOF Sep 16 '17 at 12:21
  • you can also use #define for declaring constants, then you can use this in array deceleration. – Pramod Yadav Sep 16 '17 at 12:22
  • 1
    Or Use `enum` like `enum { array_size = 1 }; int a[array_size];`. – BLUEPIXY Sep 16 '17 at 12:36
  • Or, if there are resonable contraints anyway, just over-declare, eg 'int a[65536];' and use a bit of it, as 'i' requires. – Martin James Sep 16 '17 at 12:58

0 Answers0