We have 2 types of consts in Zig. Real consts and immutable consts.
How can I know the difference (for sure)?
And here, when I make this one a global:
const SOME_SET = std.EnumSet(MyEnum).initMany(...);
or I put this inside a local function.
Is that const in both cases put in some ‘constant memory area’ of my exe?
I think you’re referring to runtime-known consts and comptime-known consts.
Local mutable variables live on the stack.
Global mutable variables live on the mutable data section of the executable.
Runtime-known consts are always local, and live on the stack like local mutable variables, but the language will ensure you don’t change them. This does allow for optimizations from the compiler.
Comptime-known consts open up more places for data to live. They can live on the stack or the constant data section of the file.
Tecnically, it wouldn’t be wrong for them to live in the mutable data section of the file. This could decrease file size, but it could negatively affect performance, because every time one of its neighbors get mutated, the cache line would get invalidated, and the data would have to be needlessly reloaded.
They can also live in the code section of the file, right next to the instructions. This is a cache optimization technique. When the instructions get cached, the data tags along, saving you one cache load.
They can even be embedded right into the code itself. For example, the expression a += 1
, in 32-bit x86, could be compiled to inc a
, which is an instruction that increments by exactly 1. In this case, the 1 is nowhere to be seen, it has become part of the code itself.
Note that variables (mutable or not) can never live of the heap. In order to put data on the heap, you call an allocation function that returns a pointer. The variable is the pointer, which is going to live in one the places where variables can live. Any manipulation of that heap data will have to happen through the pointer.
Aha aha, thanks, it is (of course) a bit more complex.
Yes I meant ‘comptime known const’ versus a ‘local const’ (assignment).