3 ms·
It should be noted that the first example can be implemented in C as well: static inline void *null_throws_helper(void *p, const char *msg) { if (!p)
by kccqzy 7y ago
It should be noted that the first example can be implemented in C as well:
static inline void *null_throws_helper(void *p, const char *msg) {
if (!p) {
fputs("uh oh: ", stderr);
fputs(msg, stderr);
fflush(stderr);
abort();
}
return p;
}
#define nullthrows(arg) null_throws_helper((arg), #arg)
In C with the GNU statement expression extension, the above can be more concisely written:
#define nullthrows(arg) \
({ \
void *p = (arg); \
if (!p) { \
fputs("uh oh: ", stderr); \
fputs(#arg, stderr); \
fflush(stderr); \
abort(); \
} \
p; \
})
With C++, you can do better by preserving the original type of pointer, or throw an actual exception rather than terminating the program.
The C/C++ preprocessor macro system isn't great, but it's good enough to be really useful. For great design, I'd lean towards the hygienic syntax-rules system used by Scheme.
- bjoli 7y agoComplex macros needs to allow breaking hygiene unless you have a particularly masochistic stroke. I am a very big fan of r6rs syntax-case which I find is the sweet spot between the comfort of being able to break hygiene and still being able to trust your macro output is not shadowing any bindings.
- jlg23 7y agoIn CL one uses gensym to introduce a macro-local symbol, or, for multiple symbols, with-gensyms as provided by the Alexandria library. No need for unhygienic macros at all.
- bjoli 7y agoDefmacro can be implented in 7 lines of syntax case, and gensym is in syntax case as well. The difference is that CL has you jumping through hoops to have something resembling hygiene, whereas it is default in scheme. It is one of many ideological differences, and I dont understand why that one has become so divisive.