Function call mask in C / C ++

If a function is, say, foo()

called differently on varius platforms, is it a bad idea to use a macro?

For example:

#ifdef WIN32
#define ffoo(a) foo(0)
#else
#define ffoo(a) foo(a)
#endif

      

+3


source to share


3 answers


Yes it is. Macros are not familiar with the scopes or the context in which they are placed, they are executed before the actual compilation phrase and replace those found.

Let ffoo

's say you want to use the name somewhere else, perhaps as a method name for a class, or even another function:

int MyClass::ffoo(int y) {}

      

This will unexpectedly cause a compilation error because it ffoo(...)

will be expanded to a function call, the wrong tokens in the wrong place.



A very common and bothersome example of this is a macro named min

and max

defined in the Windows API, once you try to use a C ++ function std::numeric_limits<T>::max()

, for example, you find bad design.

Your best alternative would be a built-in function, as they respect the semantics of the language as they are functions.

#ifdef WIN32
inline int ffoo(int a) { return foo(0); }
#else
inline int ffoo(int a) { return foo(a); }
#endif

      

If you're in a C89 environment that doesn't support the keyword inline

, you can use static

given the size of this call, it won't hurt.

0


source


In C ++ this is considered bad practice, there you have so many other possibilities like inheritance, overloading, etc. that you really don't need it.



+3


source


As you know, creating macros using #define

invokes undefined behavior. I would recommend using templates instead of macros.

A simple example from the book Effective C ++:

#define CALL_WITH_MAX(a,b) f((a) > (b) ? (a) : (b))

      

Produces different behavior when called like this (try it):

CALL_WITH_MAX(++a,b); // a is incremented twice
CALL_WITH_MAX(++a,b+10); // a is incremented once

      

If you are using C you are more limited as you do not have any object oriented templates or workarounds.

+2


source







All Articles