Constants - Manhunter07/MFL GitHub Wiki

Constants may be declared with an own name rather than just used as direct values in code. You can declare any value as a constant in MFL. Constants are similar to variables, but cannot be re-declared. In that regard, they are treated like functions returning a constant value, but are faster and easier to use since the compiler does not need to place a function call and extend the call stack. Unlike functions and variables, constants cannot be addressed and therefore not passed as references. Instead, the compiler decides which value kinds are passed as references and which are not. There is no difference in behaviour inside normal expressions between named and unnamed constants. For very complex structures, named constants may be slightly more performant, and especially more convenient to use.

Declaration

Constants are declared with a const keyword in the beginning of the expression. After that comes the name of the constant as we want to later call it by. This name follows the general and overall-valid restrictions for identifiers, such as variable and function names.

const DaysPerYear = 365

Since constants cannot be overwritten, they require an initial value that they keep for their life time. This is divided from the identifier by an equals sign and can be any expression to be evaluated right away. With that in mind, we could also write the above code like this, and would not change the program at all:

const DaysPerYear = 4 * 30 + 7 * 31 + 28

Of course, constants may be of any data-type, including numbers, records, references, strings and arrays. They may also use other contants (not themselves, obviously), variables or functions in their definitions. Constants can be declared locally.

Usability

Constants can be used anywhere within their scope using their unique identifier. In contrast to functions, constants' values are evaluated once at the time of declaration and stay the same. This applies even when their value is built from variables or functions that may have different values already at the time the constant is used for the first time. In the following code, the constant will therefore always return "Initial", even though it had been declared using a variable that changed its value later on:

var MyVar = "Initial"
const MyConst = MyVar
var MyVar = "New"
MyConst \still returns "Initial"\