2

Possible Duplicate:
Declaring an array with a non-constant size variable

This is my code:

const int xsize=150;
char Hey[xsize];

I don't understand why I cannot declare my new array Hey using the constant above. Can anyone help in this?

Community
  • 1
  • 1
piggyback
  • 9,034
  • 13
  • 51
  • 80

3 Answers3

3

It's not valid C89 code. You can't declare an array with variable size, even if the variable happens to be const.

It would work if you had it as a #define rather than a const int. It is valid in C99, though. GCC and other compilers also offer it as an extension in C89 mode.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
  • GCC allows it in C++ as a language extension with `-std=gnu++98` (the default.. or is it still?) or with `-std=gnu++11`. – Kos Nov 05 '12 at 11:28
  • Note: It is only valid C99 in block scope, at file scope, you still need a _constant expression_ for the size. – Daniel Fischer Nov 05 '12 at 11:36
1

Because const does not create a constant. It creates a read-only object.

The difference between object and constant is that objects have a specific memory location they live at; constants live only in source code.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

In C89, an array size should be a constant expression. A const variable is not a constant expression. To do this, you have to use rather VLA, from C99.

md5
  • 23,373
  • 3
  • 44
  • 93