Arrays
CaffeineC doesn't have builtin support for arrays, but they are still possible to create.
Defining a new array
Finding out how much memory we need
To create a new array, you have to know what data type will be stored inside. You will then have to find out, or calculate the memory (in bytes) that will be required to store one instance of the type. So for example a 64 bit integer (i64
type) requires 8 bytes. If you want to store 10 64 bit integers, you will need 10 x 8 bytes of memory.
Allocating the memory
To allocate the memory required, we will need to use the malloc
function from C. To use it in CaffeineC, we need to define the external function. We can do this using this simple syntax
Then in our main function we can call the function to allocate the necessary memory
Casting the allocated memory to the correct data type
Next we need to cast our allocated memory to the correct data type using the bitcast expression.
We can also simplify this to work as a one-liner:
Accessing elements in the array
Once we have created our array, accessing it is pretty simple. You can do it using [] just like in other languages.
Last updated