chasep255
chasep255

Reputation: 12175

Static arrays inside of functions error C

static const int LOG_MAX = 31;
static int log_table[LOG_MAX];

This code is inside of a function in C. When I try to compile I get the error:

"main.c:19:16: error: storage size of 'log_table' isn't constant".

I don't understand this since LOG_MAX is const.

Just to clarify this is C code and I am using GCC.

Upvotes: 2

Views: 2179

Answers (5)

unwind
unwind

Reputation: 399833

This fails since a const int variable is not considered a compile-time constant in C.

But since the array is going to be static, you can be sure that the "full" declaration is always available, i.e. it's never going to be referenced through a pointer. Thus, you can inline the size and use sizeof in all places where you wanted to use LOG_MAX:

static int log_table[32];

and then elsewhere in the same function:

const size_t log_max = sizeof log_table / sizeof *log_table;

This keeps the "magic constant" around, but only in one place and its purpose should be pretty clear given the way the log_table is used. This is all inside a single function, after all, it's not scary global data.

Upvotes: 1

Lundin
Lundin

Reputation: 213842

In older C and C++ standards, the array bounds of an array had to be a constant literal evaluated at compile time. A const variable isn't necessary evaluated at compile time, it could be created in runtime as a local variable. Also, as pointed out in another answer, const should actually be regarded read-only rather than anything else.

In all C and C++ standards, static arrays must always have their size set using a constant literal. (Or to be picky, this applies to any variable with static storage duration)

In newer C standards (C99, C11) however, the code you posted is perfectly fine if you leave out the static keyword. It will then create a variable-length array (VLA), which may or may not be what you wanted to do.

I'm not sure about the latest C++11 standard, but as far as I know it does not support VLAs.

Upvotes: 4

jan
jan

Reputation: 1

You should use the preprocessor :

#define LOG_MAX 31
static int log_table[LOG_MAX];

Upvotes: 0

ouah
ouah

Reputation: 145839

const does not mean constant in C but rather read-only. LOG_MAX is not a constant in your program.

Here are two ways to have a constant:

#define LOG_MAX 31

or

enum {
    LOG_MAX = 31
};

Upvotes: 3

Olotiar
Olotiar

Reputation: 3274

This isn't valid C, even though the int is const and static. I would recommend doing something like

#define LOG_MAX 31
static int log_table[LOG_MAX];

Upvotes: 1

Related Questions