What C macro is in your opinion is the most useful? I have found the following one, which I use to do vector arithmetic in C:
#define v3_op_v3(x, op, y, z) {z[0]=x[0] op y[0]; \
z[1]=x[1] op y[1]; \
z[2]=x[2] op y[2];}
It works like that:
v3_op_v3(vectorA, +, vectorB, vectorC);
v3_op_v3(vectorE, *, vectorF, vectorJ);
...
also multi-type Minimum and Maximum like that
If you need to define data multiple times in different contexts, macros can help you avoid have to relist the same thing multiple times.
For example, lets say you want to define an enum of colors and an enum-to-string function, rather then list all the colors twice, you could create a file of the colors (colors.def):
Now you can in your c file you can define your enum and your string conversion function:
The key point with C macros is to use them properly. In my mind there are three categories (not considering using them just to give descriptive names to constants)
In the first case, your macro will live just within your program (usually just a file) so you can use macros like the one you have posted that is not protected against double evaluation of parameters and uses
{...};
(potentially dangerous!).In the second case (and even more in the third) you need to be extremely careful that your macros behave correctly as if they were real C constructs.
The macro you posted from GCC (min and max) is an example of this, they use the global variables
_a
and_b
to avoid the risk of double evaluation (like inmax(x++,y++)
) (well, they use GCC extensions but the concept is the same).I like using macros where it helps to make things more clear but they are a sharp tool! Probably that's what gave them such a bad reputation, I think they are a very useful tool and C would have been much poorer if they were not present.
I see others have provided examples of point 2 (macros as functions), let me give an example of creating a new C construct: the Finite state machine. (I've already posted this on SO but I can't seem to be able to find it)
that you use this way:
You can add variation on this theme to get the flavour of FSM you need.
Someone may not like this example but I find it perfect to demonstrate how simple macros can make your code more legible and expressive.
I also like this one:
And how you macros-haters do fair floating-point comparisons?
Find the closest 32bit unsigned integer that is larger than x. I use this to double the size of arrays (i.e. the high-water mark).
for-each loop in C99: