C: warning for #define

Looking for a simple #define i found this warning:

Multiple evaluation of side effects

in the link: http://en.wikipedia.org/wiki/C_preprocessor

the essence of which is that for instance

#define MIN(a,b) ((a)>(b)?(b):(a))

evaluates variables multiple times, producing bad effects....(typically where you can loose some time finding out about it....)

illustration from this text:
if MIN(++firstnum,secondnum) is evaluated, then firstnum may be incremented twice
(what??? MAY be......so, once in a while? or just on a MAC???)
anyway, the solution is:

http://en.wikipedia.org/wiki/Typeof

making a primitive kind of clones, with "typeof"

#define max(a,b) \
       ({ typeof (a) _a = (a); \
           typeof (b) _b = (b); \
         _a > _b ? _a : _b; })
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: