Russell Shaw <rjshawN_o@s_pam.netspace.net.au> wrote:
Richard Bos wrote: Russell Shaw <rjshawN_o@s_pam.netspace.net.au> wrote:
How do i make an if/then/else macro act as a function
so that the whole thing looks like the return value?
You don't. That's what the ?: operator is for.
I tried this lame attempt for starters:
#define A_FROM_B(b) \
( \
if(b < 10) { \
a = b; \
a? What is a? What happens if I call this macro in a function where a is
a struct?
Like i said, it's a lame one;)
} \
else { \
a = 2*b; \
}, \
a; \
)
#define A_FROM_B(b) ((b)<10? (b): 2*(b))
Note the parens around b in the definition of the macro. They will save
your bacon some day when you decide to call A_FROM_B(x+10).
Richard
What do i do with things that contain more complex statements like:
if(size > 0x1ff) {
size_t sz = size;
for(ndx = 0; ndx < 32; ndx++) {
if(sz <= 0) {
break;
}
sz >>= 1;
}
ndx -= 8;
ndx <<= 9;
}
else {
ndx = size;
}
Do i have to make it into a function?
You can make a macro out of that, e.g.
#defined STRANGE_MACRO( size, ndx ) \
do { \
if ( ( size ) > 0x1ff) { \
size_t sz = ( size ); \
for ( ndx = 0; ndx < 32; ndx++ ) { \
if ( sz <= 0 ) \
break; \
sz >>= 1; \
} \
ndx -= 8; \
ndx <<= 9; \
} \
else \
ndx = ( size ); \
} while ( 0 ) \
but I would rather recommend to make that a function. Macros can
easily break when not written and used very carefully. If you e.g.
call it as
STRANGE_MACRO( size++, ndx );
then 'size' gets incremented two or three times instead of just
once as you would expect from a function call because a macro i
a simple text replacement (you could avoid that here by introdu-
cing another variable in the block and assigning the value of
'size' to it just once instead of evaluating it several times
in the macro). And, of course, if you try to call it like this
STRANGE_MACRO( size, ndx + 1 );
you'll ge a syntax error that's probably very hard to find. So why
not make the whole thing into a function?
BTW, in that macro you use a shift operation on 'sz' but also test
it for being less or equal to 0. But you can only use shift operations
safely on unsigned integers.
Regards, Jens
--
\ Jens Thoms Toerring ___
Je***********@physik.fu-berlin.de
\__________________________
http://www.toerring.de