Author Topic: Explicit non-null-ness  (Read 13241 times)

lerno

  • Full Member
  • ***
  • Posts: 247
    • View Profile
Explicit non-null-ness
« 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:

Code: [Select]
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.

Code: [Select]
Foo *f1 = foo(); // Non null to nullable ok
Foo &f2 = foo2(); // Nullable to non null not allowed

A check allows conversion:

Code: [Select]
Foo *f = foo2();
assert(f);
Foo &f2 = f;

Or:

Code: [Select]
Foo *f = foo2();
Foo &f2 = f ? f : foo();

With the elvis operator:

Code: [Select]
Foo &f = foo2() ?: foo();

Using pointer without nullcheck is a warning:

Code: [Select]
Foo* f = foo2();
return f.a; // warn, f may be null.

Solution is adding the assert test, or supress null warning with an attribute

Code: [Select]
Foo *f = foo2();
return f.a @(notnull);

bas

  • Full Member
  • ***
  • Posts: 220
    • View Profile
Re: Explicit non-null-ness
« Reply #1 on: February 28, 2019, 08:03:49 AM »
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.

lerno

  • Full Member
  • ***
  • Posts: 247
    • View Profile
Re: Explicit non-null-ness
« Reply #2 on: March 01, 2019, 02:35:27 PM »
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).