I need to write a macro that operates on bitarray looking like this:
array[0] = number of bits in bitarray (integer)
array[1..n] = bits
Macro must look like:
GetBit(pointer, index)
Macro *must* return 0,1 or call function similar to exit().
This is my (working) inline-function version of macro that I'm supposed to write:
static inline unsigned long GetBit(BitArray_t array, unsigned long index)
{
if ((index) >= array[0])
exit(EXIT_FAILURE);
else
return (GetBit_wo_boundary_checks(array,index));
}
This is what I've got:
#define GetBit(array,index)\
(((index) < array[0] || exit(EXIT_FAILURE)) ?\
GetBit_wo_boundary_checks(array,index) : 0)
My problem is that this has to do index boundary check (i < p[0]) and exit before it tries to access undefined memory with GetBit_wo_boundary_checks(p,i).
I thought that I could work around this by putting exit into short-circuit evaluated condition, but I get: "invalid use of void expression".
Is there any way to make this expression macro transparently exit() when index is higher than maximum defined in array[0]?
One option would be to use the comma operator with your exit()
call, like:
(exit(EXIT_FAILURE), 0)
It's a little hack-ish, but this will make the expression return the value 0
and should satisfy the compiler.
You could use the ,
operator to do this:
#define GetBit(array,index) \
(((index) >= array[0]) \
? exit(EXIT_FAILURE), -1 \
: GetBit_wo_boundary_checks(array,(index)))
Note that index
is evaluated twice, which is not safe.
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