Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjC/C syntax: static void *const Something = (void *)&Something;

Tags:

c

objective-c

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?

like image 633
Golden Thumb Avatar asked Aug 01 '14 14:08

Golden Thumb


1 Answers

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.

like image 171
Fabian Avatar answered Nov 11 '22 22:11

Fabian