Saturday, December 17, 2016

basic C macros

Macros in C generally have a bad reputation that's based on mostly obsolete or incorrect information, this post is an attempt at shining some light into that corner.

code blocks

Passing code blocks as macro parameters is useful for splicing user defined code into a template and returning the result. libc4life's 'C4LAMBDA' uses the technique to define a nested function and return it's address in one statement.


repeated side effects

One of the more popular objections to C macros is the risk of repeatedly evaluating code with side effects. This risk is not unique to C; it comes with the basic capability to paste the same code repeatedly. In many cases it's possible to get around the issue by declaring temporary variables to hold the result of evaluating parameters once. libc4life uses that technique to implement a safe MAX macro.


identifiers

libc4life provides macros for appending one identifier to another and for generating unique identifiers.


variable injection

There is nothing wrong with injecting variables into user code, as long as that is the intended outcome. libc4life's provides a macro that allocates memory from the stack and gives the user full control of the pointer when specifying the parameter list for the provided function.


naming conventions

Naming conventions are useful for defining operations on top of protocols with multiple implementations. Most abstractions in libc4life come with an '_init' function, and the library provides a macro to simplify initializing stack allocated memory for any abstraction that implements that protocol.


for loops

The standard for loop comes with additional possibilities to use 'break' and 'continue' as part of the macro's sematics. libc4life uses for loops to implement channel operations that can be aborted by calling 'break'.


code generation

All macros generate code, but some of them deserve being called code generators more than others. libc4life includes a code generator to declare a lazy initialized static variable of user specified type in one statement.


May a thousand macros bloom, and may Source be with you...

peace, out