Set type
Alexis Dimitriadis
alexis at reed.UUCP
Tue Feb 26 17:08:15 AEST 1985
> Creating sets in C is easy. To declare set element, use #define:
>
> #define RED 01
> #define BLUE 02
> #define GREEN 04
>
> C has a union operator ("|"), an intersection operator ("&"), and even
> a set difference operator ("&~"). Of course, this approach limits you
> to sets which contain no more elements than are contained in an integer,
> but this limitation also tends to apply to PASCAL sets.
Actually, it is easy to have bitfields of arbitrary length. (And no,
Pascal sets are not necessarily limited to one word). Define each
element to correspond to an *integer*. Then define a set as an array of
enough integers to contain a bit for each potential element. Then
membership of an element is implemented by turning on the bit of <elementh>
order. I saw somewhere the following macro that will do the job:
#define setbit(field, bit) (field[(bit)/WORDSIZ] |= (1<< ((bit)%WORDSIZ)))
Which, for WORDSIZ == 32, can be optimized to
#define setbit(field, bit) (field[(bit)>>5] |= (1 << ((bit) & 037))
Similar macros can test or unset bits. Operations between sets can be
optimized with functions that mask entire words at a time...
Sorry if I contribute to the torrent of messages that will soon say the
same thing...
Alexis Dimitriadis
More information about the Comp.lang.c
mailing list