1

In C I can do something like

#define SIZE 16
int c[SIZE];

but in Vala when I do

const int SIZE = 16;
int c[SIZE];

I get error during compiling that ends with "undeclared here (not in a function)"

Is there any way to remove magic numbers in vala and replace them with constants?

  • 1
    Do you think `#define SIZE 16` and `const int SIZE = 16;` are same? – haccks Oct 27 '15 at 06:35
  • of course not, but it's the closest thing I could think of – Daniel Hladík Oct 27 '15 at 06:44
  • Where you placed `int c[SIZE];`? Inside `main`/function or you declared it as global? – haccks Oct 27 '15 at 06:46
  • I placed constant and array in same class that I create(call) in main – Daniel Hladík Oct 27 '15 at 06:52
  • I am not able to figure out the actual problem. It would be helpful to us if you will post some more code. – haccks Oct 27 '15 at 06:54
  • Possible duplicate of [why the size of array as a constant variable is not allowed in C but allowed in C++?](http://stackoverflow.com/questions/25902512/why-the-size-of-array-as-a-constant-variable-is-not-allowed-in-c-but-allowed-in) – phuclv Oct 27 '15 at 06:55
  • [“static const” vs “#define” in C](http://stackoverflow.com/q/1674032/995714), [Can a const variable be used to declare the size of an array in C?](http://stackoverflow.com/q/18848537/995714) – phuclv Oct 27 '15 at 06:57
  • @LưuVĩnhPhúc The answers you linked explain the difference between a constant and a preprocessor define, but Vala doesn't have a preprocessor (only conditional compilation). So this question is not a duplicate. – Jens Mühlenhoff Oct 27 '15 at 10:45

1 Answers1

1

Dynamic allocation is the way to go:

const int SIZE = 16;
int[] c = new int[SIZE];

Especially if SIZE is part of some C header file that you are binding to via a vapi file.

In the vapi case static allocation works as well:

mylib.h

#define MYLIB_SIZE 16

mylib.vapi

namespace Mylib {

    // You can optionally specify the cname here:
    //[CCode (cname = "MYLIB_SIZE")]
    const int SIZE;
}

main.vala

int c[Mylib.SIZE];
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113