C2 forum
General Category => Ideas => Topic started by: lerno on February 02, 2019, 12:28:24 PM
-
I suggest we reuse & arg to mean a pointer that is guaranteed to be non-null.
Consider the following methods:
Foo& foo();
Foo* foo2();
void bar(Foo& f);
void bar2(Foo* f);
Unlike in C++, both Foo& and Foo* are pointer, the former guaranteed to be not null.
Foo *f1 = foo(); // Non null to nullable ok
Foo &f2 = foo2(); // Nullable to non null not allowed
A check allows conversion:
Foo *f = foo2();
assert(f);
Foo &f2 = f;
Or:
Foo *f = foo2();
Foo &f2 = f ? f : foo();
With the elvis operator:
Foo &f = foo2() ?: foo();
Using pointer without nullcheck is a warning:
Foo* f = foo2();
return f.a; // warn, f may be null.
Solution is adding the assert test, or supress null warning with an attribute
Foo *f = foo2();
return f.a @(notnull);
-
In C++ a reference is also a pointer that's 'guaranteed' to be non-null. This can work because a function in C++ can return
an object itself that's turned into a reference. I don't see how this could work in C because C doesn't have copy-constructors etc.
-
Semantic analysis can guarantee non-nullness. Don't confuse it with C++, it's just borrowing the operator. int &a means int *a @(non-null).