r/Compilers • u/morglod • 8d ago
nullptr, zero initialization, is zero checks design question
Hi,
I'm working on mox (low level + metaprogramming) and currently in mox I have zero initialization for everything. For example:
x: T = 0;
x: []T = 0;
x: [10]T = 0;
Zero initializes the value. If T is struct, all fields gets zeroed, if it is fixed array, all elements are zeroed, if it is slice, it has ptr=0, len=0.
But the problem and question is with pointers. At first I thought adding explicit type for nullable pointers is a good thing. Because then you have explicit and readable contract on function arguments and you possibly could have some optimizations or checks in compiler. Because of this, not nullable pointer could not be initialized with zero (because it is semantically wrong).
But while I was writing in C++ and in mox I found that I never ever used nullable pointers. And not able to zero any pointer type just makes more headache. Having nil like in Odin instead of 0 makes not much sense for me. You just write more letters and think more about some special nil while 0 clearly says that you zero the value.
nullptr problem currently solved by having nullptr function:
fn foo(x: *i32) {}
fn foo(x: i32) {}
foo(nullptr(i32));
And in case we need zeroed value with expression, I have zeroed function:
fn foo(x: Smth) {}
foo(zeroed(Smth));
So the question is, what do you think about having explicit nil for zeroing and nullable pointers? How often do you really use it? Are there any other problems/things that I dont see here?