Codementor Events

X-Macros

Published Feb 06, 2019

the X-Macros are a powerful technique that helps us reduce run time errors on c programs buy using the preprocessor capabilities.
it's a lot more easier to exaplain the x-macros by an example.
so suppose that in your programs you have the following enum -
enum1.png

you also have a function that returns the color of the car that looks as follows -
enum2.png

now, suppose that you need to add a new car to the enum. lets say that the new enum entry is CHEVROLET. you have to update the GetCarName function to support this new type. if you don't do so then when your program calls GetCarName(CHEVROLET) the function returns NULL which can cause an undefined behavior to the program.

here comes the big advantage of using X-Macros.i will ddemosrate how to write the above example using X-Macros.
first we declare the following macro in the header file -
macro.png

next we declare our enum -
macro2.png

take a look at the new enum declaration above. it's a bit tricky at first glance. the preprocessor will only take the first argument of each CAR_ENTRY and place it in the enum. so the enum will look like this after the preprocessing stage -

great!, this is the first step of what we wanted to achieve.
next we'll go to our c file and define the following macro -
macro3.png

again, after the preprocessing stage, the above variable will look as follows -
var3.png
now lets refactor the GetCarName function -

var1.png

wow, we reduced the function's length to a single line!.
now, whenever we want to add a new car, we simply add a new line to the CAR_ENTRIES macro.
adding a line to this macro requires you to set both an enum name and a car's color and there is no need to add extra code in any other place!.
so sticking to our initial example, if i were to add the CHEVROLET as a car, i will simply add it to the CAR_ENTRIES macro -
macro4.png

this was a small taste of the X-Macros. the X-Macros can be very helpful in create simplicity in many other cases.
the X-Macros might seem hard in the begging, but once you get used to them you will find yourself use them a lot.

Discover and read more posts from shai ben shalom
get started
post commentsBe the first to share your opinion
Show more replies