Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name of c idiom – `static void *thing = &thing;`

Tags:

c

The code:

static const void *const uniquePtr = &uniquePtr;

…will provide a unique void pointer in the compilation unit. It's handy for generating a unique handle or name for APIs that like to take a name as a void* in this way.

Examples of use:

  • objc_setAssociatedObject and objc_getAssociatedObject
  • addObserver:forKeyPath:options:context:

It'd be sensible to wrap this pattern in a macro to avoid making a mistake with it, and to encapsulate the idea so that it self documents.

But that leads to the question: is there a name for this idiom that can be used to name the macro?:

#define DECLARE_VOID_THING(name) static const void *const name = &name
DECLARE_VOID_THING(aHandle);
DECLARE_VOID_THING(anotherHandle);

Any thoughts?

like image 785
Benjohn Avatar asked Mar 11 '15 09:03

Benjohn


2 Answers

As was hashed out above there is (very likely) no standard parlance, so you're free to choose whatever you think best. Perhaps something like UNIQUE_VOID_POINTER or some such.

like image 74
John Hascall Avatar answered Oct 15 '22 21:10

John Hascall


I would call it a self reference it is not very different from:

struct self {
   struct self *moi;
   } me = { &me};

This has the additional advantage that you don't have to dereference a void* pointer in order to use it. (eg: assert (me.moi == &me); )

like image 32
wildplasser Avatar answered Oct 15 '22 21:10

wildplasser