C macros
When doing an assignment I came across this strange statement:
#define ensure_successful_malloc(ptr) \
if (ptr == NULL) { \
perror("Memory allocation unsuccessful for" #ptr "\n"); \
exit(1); \
}
Turns out this is not really a function, but a macro.
You can use #define
to define constants (which is what I saw so far), but you can use it for the above as well, to define macros.
Macros take arguments, which must be valid C identifiers. They then replace the callsites with the string expressions (which is why you should note the ’' character used to escape)
I guess the benefit is that code is inlined by the preprocessor?