0

I'm defining a variable as integer and want to use thati

int specLength = 17;
int spec[specLength-1];

When I do this, I get the following error message:

 TestProgram:34: error: array bound is not an integer constant before  ']' token
 int spec[specLength-1];

But when I set it up as

int specLength = 17;
int spec[16];

it all works fine.

What is the magic here?

Many thanks

1

You have to use a constant expression, one that produce always the same value.

const int specLength = 17;
int spec[specLength - 1];

Otherwise, the compiler won't know how much space reserve for the array.

The problem with C/C++ is that the compiler doesn't really know if a variable is modified somewhere or not (thru pointers, for example). You have to tell the compiler that something is static, not changing.

You can also use a #define for the same porpuse:

#define SPEC_LENGTH 17
int spec[SPEC_LENGTH]

Why both? const int val=17 means that val has a type (int). Using #define is just a text search-and-replace before compiling. So, SPEC_LENGTH has no type at all. If needed, you have to use a cast, like (int) SPEC_LENGTH.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.