[fpc-pascal] Optional param modifier

Martin Frb lazarus at mfriebe.de
Sat Apr 13 20:45:05 CEST 2019

On 13/04/2019 19:04, Ryan Joseph wrote:
> Ok, here’s a historic real work example which is all too common:
>    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
> Can you pass null for attr? Well you need to read the man page and read through multiple paragraphs to find out "If attr is NULL, then the thread is created with default attributes.” See: http://man7.org/linux/man-pages/man3/pthread_create.3.html
> Clearing up this situation with a tiny little syntax is all I propose. Make that fact known in code and force pthread_create to check if attr is nil before dereferencing it.

Well that doesn't work. Unless you wrote pthread_create (or whatever 
other function).
Because the "opitonal" parameter (which really only serves as 
documentation hint) is itself optional.
So if the author of the code that you intend to use did not put 
"optional" in there, you are still where you are now. And you cant force 
the author to put it there. Same as you cant force the author to put it 
on top of the documentation.

Already today the author could add a comment (even pasdoc) to the 
declaration. And it serves the same effect.

Also the is a difference between:
- the parameter is nil-able (better term that optional, optional has a 
different meaning)
- the compiler needs to enforce an check for "<> nil"

If the parameter is only stored, for later usage, then the nil can be 
stored too. There is no check needed for that.
It will be needed later in some other function, but the compiler can not 
know where that may be.

You can even call methods on an object that is nil. So long as they are:
- not virtual, nor call virtual methods themself
- do not access "self" without prior check that it is not nil

More information about the fpc-pascal mailing list