-
Macros
I have a question about using macros in C.
First, I am trying to divide and return both the answer and the remainder from a macro. Right now I have:
Code:
#define DIVMOD(x,y,d,r) ((y)==0 ? d=0; r=0 : (d = (x)/(y); r = (x) % (y))
which I know is not correct. Any suggestions on how I could do this?
Thank you.
-
Why would you use a macro for that? You can't return values from macros, a macro is not a function, it is a substitution. You could try to create a macro which has two "output-variables". In the "call" to the macro pass the addresses of those variables and in the macro use the usual operations you would do to assign values to such variables.
-
This works for me:
Code:
#define DIVMOD(x,y,d,r) d = ((y)==0) ? 0, r=0 : (x)/(y), r = (x) % (y)
but I agree with Shiro that this is quite a nasty bit of code. A function would be much neater...
Code:
void DivMod(int x, int y, int * pd, int * pr)
{
if (y == 0)
*pd = *pr = 0;
else
{
*pd = x / y;
*pr = x % y;
}
}
...and unless you are doing loads of these operations isn't going to significantly slow down your program.
If you insist on using a macro use something like:
Code:
#define DIVMOD(x,y,pd,pr) *pd = ((y)==0) ? 0, *pr=0 : (x)/(y), *pr = (x) % (y)
where pd and pr are pointers.
-
Quote:
Originally posted by DavT
If you insist on using a macro use something like:
Code:
#define DIVMOD(x,y,pd,pr) *pd = ((y)==0) ? 0, *pr=0 : (x)/(y), *pr = (x) % (y)
where pd and pr are pointers.
What's the purpose of using pointers? It's just a macro. It's not a function call.
Quzah.
-
It's probably just a personal hang-up, but I I really dislike macros.
I think they lead to confusing code. The only excuse I've ever come across for using a macro where a function would do the job is in some kind of real-time signal processing situation where you can't afford the overhead of a function call and the compiler doesn't support the 'inline' (or similar) keyword.
In the flow of the program I find it really disconcerting (or downright confusing) to find something that looks like a function call but (taking an example at random) returns values via non-pointer arguments.
Just my personal point of view....:)