a very occasional diary.

nondescript

Labels

2012-05-11

A macro.


C language is wonderfully profound. After almost 20 years, I still find new ways to (ab-)use it. Here is a little problem:
Define a macro IN(x, set), called as
IN(x, (v0, v1, ..., vn))
that expands into an expression
((x) == (v0) || (x) == (v1) || ... (x) == (vn)) 
which evaluates to true iff x is a member of set {v0, ..., vn}, where the type of x and all vs is the same. Alternatively, define a macro IN1(x, ...) that expands to the same expression as IN(x, (...)).

2 comments:

  1. I don't want to spoil the fun for other readers.

    (base64 -d)

    ----BEGIN SOLUTION----
    I2RlZmluZSBGKHgsIHYsIHApICAoeCkgPT0gKHYpIHx8IHAKCi8qIEFSR04oLi4uKSBldmFsdWF0
    ZXMgdG8gdGhlIGxpdGVyYWwgbnVtYmVyIG9mIHRoZSBwYXNzZWQtaW4gYXJndW1lbnRzLiAqLwoj
    ZGVmaW5lIEFSR05fKF8sXzY0LF82MyxfNjIsXzYxLF82MCxfNTksXzU4LF81NyxfNTYsXzU1LF81
    NCxfNTMsXzUyLF81MSxfNTAsXzQ5LF80OCxfNDcsXzQ2LF80NSxfNDQsXzQzLF80MixfNDEsXzQw
    LF8zOSxfMzgsXzM3LF8zNixfMzUsXzM0LF8zMyxfMzIsXzMxLF8zMCxfMjksXzI4LF8yNyxfMjYs
    XzI1LF8yNCxfMjMsXzIyLF8yMSxfMjAsXzE5LF8xOCxfMTcsXzE2LF8xNSxfMTQsXzEzLF8xMixf
    MTEsXzEwLF85LF84LF83LF82LF81LF80LF8zLF8yLF8xLG4sLi4uKSAgbgojZGVmaW5lIEFSR04o
    Li4uKSBBUkdOXygwLF9fVkFfQVJHU19fLDY0LDYzLDYyLDYxLDYwLDU5LDU4LDU3LDU2LDU1LDU0
    LDUzLDUyLDUxLDUwLDQ5LDQ4LDQ3LDQ2LDQ1LDQ0LDQzLDQyLDQxLDQwLDM5LDM4LDM3LDM2LDM1
    LDM0LDMzLDMyLDMxLDMwLDI5LDI4LDI3LDI2LDI1LDI0LDIzLDIyLDIxLDIwLDE5LDE4LDE3LDE2
    LDE1LDE0LDEzLDEyLDExLDEwLDksOCw3LDYsNSw0LDMsMiwxLDApCgojZGVmaW5lIEZPTERfMV8o
    eCwgdjEpICAgICAgICAgICAgICBGKHgsIHYxLCBmYWxzZSkKI2RlZmluZSBGT0xEXzJfKHgsIHYx
    LCB2MikgICAgICAgICAgRih4LCB2MSwgRk9MRF8xXyh4LCB2MikpCiNkZWZpbmUgRk9MRF8zXyh4
    LCB2MSwgdjIsIHYzKSAgICAgIEYoeCwgdjEsIEZPTERfMl8oeCwgdjIsIHYzKSkKI2RlZmluZSBG
    T0xEXzRfKHgsIHYxLCB2MiwgdjMsIHY0KSAgRih4LCB2MSwgRk9MRF8zXyh4LCB2MSwgdjIsIHYz
    KSkKLyogLi4uICovCiNkZWZpbmUgRk9MRF9JKG4pICAgICAgICAgRk9MRF8gIyMgbiAjIyBfCiNk
    ZWZpbmUgRk9MRF8oeCwgbiwgLi4uKSAgRk9MRF9JKG4pKHgsICMjX19WQV9BUkdTX18pCiNkZWZp
    bmUgRk9MRCh4LCAuLi4pICAgICAgRk9MRF8oeCwgQVJHTihfX1ZBX0FSR1NfXyksIF9fVkFfQVJH
    U19fKQojZGVmaW5lIElOKHgsIC4uLikgICAgICAgIChGT0xEKHgsIF9fVkFfQVJHU19fKSkKCklO
    KHgsIHYwLCB2MSwgdjIsIHYzLCB2NCk7IC8qIHJlcXVpcmVzIGBGT0xEXzVfKCknLCB3aGljaCBp
    cyBub3QgZGVmaW5lZCAqLwpJTih4LCB2MCwgdjEsIHYyLCB2Myk7CklOKHgsIHYwLCB2MSwgdjIp
    OwpJTih4LCB2MCwgdjEpOwpJTih4LCB2MCk7Cg==
    ----END SOLUTION----

    Is your variant better?

    ReplyDelete
  2. It's similar, except I used __VA_ARGS__ for v2, ... in the definition of what you call FOLD_*_(), so that these definitions are equal in size for all values of '*'.

    ReplyDelete

Follow by Email