1
const int size = 10; // realna ilość danych
int tablica[size+1];

i have: variable-size type declared outside of any function

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
Domiik
  • 233
  • 1
  • 5
  • 14

4 Answers4

4

Use

#define size 10

instead of a const int. The latter is not a compile-time constant in C, but a variable that cannot be assigned to (unless via a pointer and a cast to get rid of const).

(This is a difference between C and C++.)

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
3

You could use an enum.

enum
{
    size = 10
};

int table[size + 1];
James Morris
  • 4,867
  • 3
  • 32
  • 51
3

Use:

enum { size = 10 };

This is a constant value that can be used in declarations and in case labels and so on. In C99, inside a function, the original code would not be a problem -- your array tablica would be a VLA or variable-length array (and the compiler error message is trying to say "you can't have a VLA outside a function").

Using an enum gives better traceability when you use a debugger on your code; the symbol is included in the symbol table. Typically, C preprocessor symbols are not available to the debugger, so trying to print 'size' when it is #define'd doesn't print an answer; printing 'size' when it is an enum does.

See also: "static const" vs "#define" in C

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    I knew there was definitely some good reasons to use an enum over a #define ;-) just couldn't recall what they were. – James Morris Mar 05 '11 at 14:31
1

The error is fairly self-explanatory. You can't declare a variable-length array outside of a function. Although the size of the array you're creating is, in practice, fixed at compile time, you've still technically violated the constraints of the language.

The usual choices are:

  1. Move the array into a function. (Usually the best option, remember globals are to be avoided when possible.)

  2. #define size n where n is the size you want, instead of using an int. (Usually better than "magic numbers", and pretty standard practice in traditional C.)

  3. Use a "magic number" (int tablica[11];). (Usually the last choice, though sometimes it does make more sense.)

Nicholas Knight
  • 15,774
  • 5
  • 45
  • 57