Muhammad Hewedy
Muhammad Hewedy

Reputation: 30058

Defining a pointer to refere to same variable name's reference?

In objective-c, I really cannot understand this:

void *x = &x;

my understanding is:

declare a generic pointer (hence type void*), the pointer variable name is x, and this pointer points to a reference to a variable (that should be declared already- but it is not) named x.

very confusing to me!

Upvotes: 3

Views: 153

Answers (3)

alk
alk

Reputation: 70921

For C and C++:

x gets assigned its own address. It points to itself afterwards.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

To conclude whether this declaration

void *x = &x;

is valid you should take into account two important quotes from the C Standard.

the first one says where ths scope of an identifier starts (6.2.1 Scopes of identifiers)

7 Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.

The second one says whether a pointer of any type can be assigned to a pointer to void (6.3.2.3 Pointers)

1 A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

So in this declaration

void *x = &x;

the scope of variabble x starts immediately before the assignment operator. Its complete type is void * and it can be assigned any pointer of other type. In the right hand there is expression of type void **. And according to the second quote it can be assigned to x because x is a pointer to void.

As result x will store the address of itself.

Upvotes: 5

Muhammad Hewedy
Muhammad Hewedy

Reputation: 30058

Based on understanding of @alk answer:

It is exactly as you say:

int y = 10;
void* x = &y;

But in out case, x points to itself instead of y

Upvotes: 0

Related Questions