6

I have difficulty to understand this line of code:

static void *const Something = (void *)&Something;

How can "Something" appear on both sides of the equal sign? Thx!

Edit: What does it mean? Why do we need this kind of code? Is there other alternative?

Golden Thumb
  • 2,531
  • 21
  • 20

1 Answers1

8

It means that Something is a pointer to itself in a static address space. It's usually used simply to create a unique value that can be used for keying, with functions such as objc_getAssociatedObject.

The container Something is going to end up in a fairly arbitrary location in memory, such as 0x12345. What that line of code is saying is the value of Something should be set to the address of Something (the & operator gives the address of the pointer). So you're putting 0x12345 into the memory location 0x12345. Because no other variable can occupy that memory address, Something is guaranteed to be unique with respect to any other variable created in this way.

Regarding the use of a variable on both sides of an assignment:

x = x + 1; doesn't seem strange at all, does it?

In the case of your question though, the declaration of Something is a statement that is valid before the "line" ends: static void *const Something.

int x = x + 5; is also valid, but x is uninitialized and so will likely contain a garbage value. &Something is asking for the address which is a real, non-garbage value as soon as Something was declared on the left hand side.

Fabian
  • 6,973
  • 2
  • 26
  • 27
  • Thx Fabian! By searching "objc_getAssociatedObject" I found a similar mentioning of this topic in one of the answers here: http://stackoverflow.com/questions/2846218/how-do-i-use-objc-setassociatedobject-objc-getassociatedobject-inside-an-object – Golden Thumb Aug 01 '14 at 15:32
  • Now I understand its purpose and usage. But the syntax still looks weird to me. I'm afraid I might have overlooked some basic language knowledge. So is there other similar concept like this one in ObjC/C? I mean using something on both sides of a single line of code. Or give me a guide/direction so I can continue reading. thx again :-) – Golden Thumb Aug 01 '14 at 15:41
  • Updated answer with some explanation of the syntax. – Fabian Aug 01 '14 at 16:02
  • So there are 3 mind steps: declare Something; get its address; do assignment (to itself). In x = x + 1, I thought the compiler handled the right side x first, trying to find its declaration somewhere else. – Golden Thumb Aug 01 '14 at 16:21
  • The compiler will actually resolve both sides of the assignment operator before executing the assignment. C code such as `array[3] = 12;` should make that clear. Where `array` is a pointer, `array[3]` is essentially `array + 3 * (the size of whatever the array type is)`. The RHS value is put into the 3rd position of the array. So the line `array[3]` must have been evaluated at some point first. – Fabian Aug 01 '14 at 17:05