I have a problem: I would like to use the function abs
of the library complex
.
However, I undergo an error warning me the function abs
used is #define abs(x) (x > 0) ? x : -(x)
.
Thus, I think the problem comes from my imports. Because of I also include the stdio and stdlib libraries, the compiler may use the function abs
defined in one of these libraries.
So my question is: how can I use the function abs
of the library complex
without removing any import ?
Thanks a lot in advance for your response.
Wrap parens around it.
(abs)(whatever);
This will force the compiler to use the function version because the macro no longer matches.
Function-like macros work by matching an identifier followed by a left paren (
. Since we've wrapped the function name itself in parens, we have instead an identifier followed by a right paren )
, which fails to match the macro. The parens are semantically transparent, but they inhibit the macro syntax.
IIRC, it was splint
the C checker which taught this to me. While writing a postscript interpreter, I created nice short macros to access the stack.
#define push(o) (*tos++ = (o))
#define pop() (*--tos)
Which were great until the tricky parts where they were part of an expression involving tos
. To avoid undefined behavior, I had to create function versions and use those for those tricky spots. For the new design, I skipped the macros altogether.
Edit: I've got a nagging feeling that it was actually the Coelocanthe book (Peter Van Der Linden's Deep C Secrets) where I learned this, the above situation being where I first needed it. IIRC his example involved putchar
or getchar
which are often implemented as both functions and macros in conforming C implementations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With