1.4. Value declaration

Felix allows values to be declared using the 'val' keyword.
Start C++ section to tut/examples/tut103.flx[1 /1 ]
     1: include "std";
     2: val i = 40;
     3: val j = 2;
     4: val k = i + j;
     5: print k; print "\n";
End C++ section to tut/examples/tut103.flx[1]
There are three values declared here, 'i','j', and 'k'. The first two have the type 'int', because '40' and '2' have the type int, whilst 'k' has the type 'int' because the addition function which takes as an argument a pair of 'int', returns an 'int'.

Notice you did not have to declare the type of the values. This is called 'type inference': the compiler works out the type from the initial value for you. You can declare the type of a variable if you want: the following program is equivalent to the one above:

Start C++ section to tut/examples/tut104.flx[1 /1 ]
     1: include "std";
     2: val i : int = 40;
     3: val j : int = 2;
     4: val k : int = i + j;
     5: print k; print "\n";
End C++ section to tut/examples/tut104.flx[1]
but it is never necessary for values: an initialiser must always be given. If you do declare the type, Felix will still deduce the type from the initialiser, and issue an error message if the types don't agree.

Values are constants: they cannot be modified, and, as we will see later, they cannot be addressed. This means the compiler is free to load the value into a register or perform other optimisations (including elide the storage for the value entirely).

There is a shortcut form for declaring variables using the := operator:

Start C++ section to tut/examples/tut104a.flx[1 /1 ]
     1: include "std";
     2: a := 1;
     3: b:int := 2;
     4: 
     5: c:int,(d,e) := 3,(4,5);
     6: 
     7: print a; print " ";
     8: print b; print " ";
     9: print c; print " ";
    10: print d; print " ";
    11: print e; print " ";
    12: endl;
End C++ section to tut/examples/tut104a.flx[1]