This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

| Using Macros To Keep Data In Sync Submitted by

If you've ever needed to keep multiple arrays of constant information in sync then this COTD tip is for you.
For example - here is a snippet from an imaginary profiler which needs to keep an enum, an array of strings for names and an array of budgets in sync:
In ProfileItem.h....

    enum ProfileItem
    {
    	ProfileItem_Render,
    	ProfileItem_Simulation,

    	//Add new profile item here.

    	ProfileItem_Max
    };

And in ProfileItem.cpp...

    const char * profileName[ProfileItem_Max]  =
    {
    	"Render",
    	"Simulation"

    	//Add description for profile item here.
    };

    const int Budget[ProfileItem_Max] =
    {
    	10,
    	12

    	//Add budget for profile item here.
    };

The above code can easily go out of sync unless everyone on a team is very careful and always adds new items to all three areas in exactly the same order.
An alternative to the above is to use the following technique:
In ProfileItemX.h....

    	XM(Render, 10)
    	XM(Simulation,12)
    	//Add new profile item and budget here...use format XM(item, budget)

Now in ProfileItem.h....

    enum ProfileItem
    {
    #define XM(profileItem, budget) ProfileItem_##profileItem,
    #include "ProfileItemX.h"
    #undef XM
    	ProfileItem_Max
    };

And in ProfileItem.cpp...

    const char * profileName[ProfileItem_Max]  =
    {
    #define XM(profileItem, budget) #ProfileItem,
    #include "ProfileItemX.h"
    #undef XM
    };

    const int Budget[ProfileItem_Max] =
    {
    #define XM(profileItem, budget) ##budget,
    #include "ProfileItemX.h"
    #undef XM
    };

Now you and your team only need to change one line of code to add a new profile item and macro's keep everything in sync, leaving much less chance for error.
Thanks to Matt Curtis for introducing me to this technique.

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.