Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variably modified array at file scope in C

Tags:

arrays

c

static

You can not have static array which size is given as a variable

That's why constants should be #defined:

#define a 6

This way preprocessor will replace a with 6, making it valid declaration.


Simple answer variable modified array at file scope is not possible.

Detailed :

make it compile time integral constant expression, since array length must be specified at the compile time.

like this :

#define a 6
#define b 3

Or, follow c99 standard. and compile like for gcc.

gcc -Wall -std=c99 test.c -o test.out

The problem here is variable length array with providing length may not be initialized so you are getting this error.

simply

static int a =6;
static int b =3;

void any_func()
{
int Hello [a][b]; // no need of initialization no static array means no file scope.
}

Now use for loop or any loop to fill the array.

For more info just a DEMO :

#include <stdio.h>
static int a = 6; 
int main()
{
int Hello[a]={1,2,3,4,5,6}; // see here initialization of array Hello it's in function
                            //scope but still error
return 0;
}


root@Omkant:~/c# clang -std=c99 vararr.c -o vararr
vararr.c:8:11: error: variable-sized object may not be initialized
int Hello[a]={1,2,3,4,5,6};
          ^
1 error generated. 

If you remove static and provide initialization then it will generate error as above.

But if you keep static as well as initialization the still will be error.

But if you remove initialization and keep static the below error will come.

error: variable length array declaration not allowed at file scope
static int Hello[a];
           ^     ~
1 error generated.

So variable length array declaration not allowed at file scope so make it function or block scope inside any function (but remember making it function scope must remove initialization)

NOTE : Since it's C tagged so making a and b as const won't help you but in C++ const will work fine.


When using CLANG/LLVM the following works:

static const int a = 6;
static const int b = 3;

static int Hello[a][b] =
{
    { 1,2,3},
    { 1,2,3},
    { 1,2,3},
    { 1,2,3},
    { 1,2,3},
    { 1,2,3}
}; 

(To see it in the generated assembly, one needs to use Hello so it will not be optimized out)

However, this will generate an error if C99 mode is selected (-std=c99), it will only generate a warning (Wgnu-folding-constant) if -pedantic is selected.

GCC does not seem to allow this (const is interpreted as read-only)

See explanation in this thread:

"Initializer element is not constant" error for no reason in Linux GCC, compiling C


Yea, this is annnoying:

const int len = 10;

int stuff[len];

Gives the error. I try to get away from doing #define x, because const int is a better way of declaring a constant, but then you have these cases where const int is not a true constant, even though the compiler knows full well it is.