Search code examples
cgtkconstantsvala

Vala - constant instead of magic number


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?


Solution

  • 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];