Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vala const initialization from read-write variable

Tags:

vala

I noticed Vala doesn't let you initialize a const variable from a non-const variable. Why is this? Is this a deliberate design decision or a bug/omission? Consider these Vala and C examples respectively; the Vala program fails to compile while the C program compiles and runs as expected:

Vala

void main()
{
   const int constInt = 1;
   const int a = constInt;

   int plainInt = 0;
   const int b = plainInt;

   stdout.printf("A: %d\n", a);
   stdout.printf("B: %d\n", b);
}

// Compiler output:
//   test.vala:7.18-7.25: error: Value must be constant
//   const int b = plainInt;
//                 ^^^^^^^^

C

#include <stdio.h>

int main()
{
   const int constInt = 1;
   const int a = constInt;

   int plainInt = 0;
   const int b = plainInt;

   printf("A: %d\n", a);
   printf("B: %d\n", b);
   return 0;
}
like image 579
weberc2 Avatar asked Aug 09 '26 01:08

weberc2


1 Answers

const has different meanings in Vala versus C. A C variable which is const is simply read-only, while const in Vala, is a compile-time constant, as it is in C#.

like image 99
apmasell Avatar answered Aug 11 '26 13:08

apmasell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!