Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array definition - Expression must have a constant value

Tags:

c

I am creating an array on stack as

static const int size = 10;

void foo() {
..
int array[size];
..
}

However, I get the compile error: "expression must have a constant value", even though size is a constant. I can use the macro

#define SIZE (10)

But I am wondering why size marked const causes compilation error.

like image 795
Iceman Avatar asked Jun 16 '14 13:06

Iceman


People also ask

Can you have a const array?

The keyword const is a little misleading. It does NOT define a constant array. It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.

How do you include an array in C++?

A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (such as int, float ...), name is a valid identifier and the elements field (which is always enclosed in square brackets [] ), specifies the size of the array.


2 Answers

In C language keyword const has nothing to do with constants. In C language, by definition the term "constant" refers to literal values and enum constants. This is what you have to use if you really need a constant: either use a literal value (define a macro to give your constant a name), or use a enum constant.

(Read here for more details: Shall I prefer constants over defines?)

Also, in C99 and later versions of the language it possible to use non-constant values as array sizes for local arrays. That means that your code should compile in modern C even though your size is not a constant. But you are apparently using an older compiler, so in your case

#define SIZE 10

is the right way to go.

like image 83
AnT Avatar answered Oct 21 '22 23:10

AnT


The answer is in another stackoverflow question, HERE

it's because In C objects declared with the const modifier aren't true constants. A better name for const would probably be readonly - what it really means is that the compiler won't let you change it. And you need true constants to initialize objects with static storage (I suspect regs_to_read is global).

like image 29
Yann Avatar answered Oct 22 '22 01:10

Yann