Home > Blockchain >  Function or macro definition which one to use
Function or macro definition which one to use

Time:01-30

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:

#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 ?

CodePudding user response:

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.

CodePudding user response:

would it be better to use a function or use the macro definition?

A function.

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

A function.

Keep using macro definition or migrate to function ?

Migrate to function.

  • Related