Skip to main content

Constants

Hybrix constants provide a convenient way to give a name to a value that you will use in your code, for example:

module example
const my_constant is 123

func f()
var x: int
# Assign 123 to x
x <- example::my_constant
end func
end module

Constants must be declared as members of a module or class.

Class constants

Note that a class constant is accessed using :: instead of the . operator. This is because the constant is not associated with any particular instance of the class. (The Name rules and conflicts section explains this distinction in more depth.)

For example:

class c
const my_constant is 123

func f()
var x: int
# Assign 123 to x
x <- c::my_constant
end func
end class

Unlike variables, constants are not inherited. This ensures the definition is easy to find.

class d extends c
func g()
var x: int

# Correct
x <- c::my_constant

# ⚠️ Not allowed
x <- d::my_constant
end func
end class

Constants have no storage

In Hybrix, every variable is stored in the computer's memory at a fixed memory location, and is represented by up to four bytes. When a variable stores an array or string or class object, then the variable's value is actually a pointer to that object. In other words, the variable stores the object's memory address. (This is why inset members are not declared using var.)

In the above example, x has a memory address, but my_constant does not. Unlike variables, constants are substituted ("inlined") into the code wherever they are used.

Consider this example with a string:

module example
const my_string is "hello"
end module

If no source code ever actually uses example::my_string, then the array for "hello" will not appear in your ROM binary at all. This is quite different from a data block or unused variable.

Constants must be compile-time

The value of a constant must be known at compile time, in other words not depending on any runtime calculations. For example:

module m
# ⚠️ ERROR: This kind of expression cannot be used as the value of a constant
const bad_constant is a::f()

func f(): int
return 123
end func
end module

An error is reported because the compiler will not try to evaluate the f() function to find its return value.