NOTE: I am not interested in using GCC statement expression!
I am implementing a set data structure using a Red Black Tree and to make it work for multiple types I am using macros.
This is a definition of a node:
typedef struct {
bool colour;
void* val;
void* parent;
void* left;
void* right;
}* set;
I want to create a macro function set_contains(s, t)
, that will “return” a true expression if t
is in a set s
. By “return” I mean, that I can use it as such:
if(set_contains(my_set, 6)) {
...
}
For example, the following macro “returns” a true expression if x is an odd number:
#define isOdd(x)
/* notice the lack of semicolon! */
(bool)((x)&1)
My set_contains
macro looks as follows:
#define set_contains(s, t)
do {
set it = s;
while(it && *(typeof((t))*)it->val != (t)) {
if((t) < *(typeof((t))*)it->val) it = it->left;
else it = it->right;
}
/* This is what I want to "return" */
(bool)it;
} while(0)
How can I have (bool)it
at the end of macro, so I can use the entire thing as an expression (like the isOdd
macro)? The do while
is necessary since I need to define a temp variable (it
) to iterate over the set. Of course I cannot use it
after while
, since it is undefined in that scope. Once again, I want to achieve this without using GCC statement expression.