Hi,
I was wondering how can we extend simple macro like
with static assertion - i.e verify if y is within 32 bits as shifting beyound is undefined. However this simple task seems to impossible in C. First, naive attempt would be sth likeCode:#define TOGGLE_BIT(x,y) \
(x) ^= (1 << (y))
But this won't work because preprocessor does only one pass, IOW it won't allow for other directives in #defineCode:#define TOGGLE_BIT(x,y) \
#if (y < 32)
(x) ^= (1 << (y))
#else
#error Requested bit out of integer bouds
#endif
Other apprach would be:
but then the macro is preatty much useless - you can't use t in the assignment or inside if() condition.Code:#define TOGGLE_BIT(x,y) \
static_assert((y > 31),"Out of integer bound")
(x) ^= (1 << (y))
So how can we cope with that?