Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function or macro definition which one to use

I have some macros that I use a lot

So I was thinking in my case would it be better to use a function or use the macro definition?

Example of a macro code that I use:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#define Test(Id, TName, i, FName, var1, var2, var3) do { \
    if (GetTable(Id, TName)) { \
        while (i < 5) { \
            if (GetField(Id, FName)) { \
                const char *user = PushName(Id, FName); \
                if (!CheckNameisValid(user)) \
                    continue; \
                var1 = GetTimestamp(user); \
                var2 = GetSex(user); \
                var3 = GetCntLogin(user); \
                i++; \
            } \
        } \
    } \
} while (false);

What would be better to use for as per the above code?

Keep using macro definition or migrate to function ?

>Solution :

Given how the macro is written, it would be much better to use a function for this purpose. The macro does not use any construction such as referring to a structure member whose name is passed as an argument to the macro.

The macro has multiple problems:

  • variable i is assumed to have been declared and initialized appropriately, but it is only incremented if CheckNameisValid(user) is non zero, potentially causing an infinite loop.

  • the ; should not be part of the macro expansion to allow usage as a single expression statement.

  • it is unclear if the variables var1, var2, var3 should be updated once or multiple times, and the caller has no way to tell what actually happened as a side effect of this macro.

Defining functions with clear semantics is much preferred. Don’t even worry about inline functions, modern compilers can determine which functions are worth inlining even if not defined as such.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading