Home > Blockchain >  What is int *(&) declaration in C
What is int *(&) declaration in C

Time:02-11

I came across this piece of code

int a = 10;    ---> i)
int *p = &a;   ---> ii)
int *(&q) = p; ---> iii)

Here in statement iii), q seems to look like a pointer having the same value as p(after resolving)(reason). However, while we are still defining, &q tries to get the address of q which hasn't yet been created. So, how do you logically explain this in pointer terms? Any resources to explain this is also appreciated.

NOTE: I did compile and run the code, q points to a.

CodePudding user response:

Maybe you got confused by the brackets, lets remove them:

int *& q = p;

Maybe you got confused by combination of * and & to form a reference to pointer, so lets try some obfuscation:

using T = int*;  // T is alias for pointer to int
T& q = p;

T& q = p; declares q to be a reference to a T and initializes that reference with p.

Note that C does not have references as C has them.

CodePudding user response:

int *(&q) declares a reference to a pointer. The parenthesis achieves nothing and it could as well be written as int *&q. It's a rather pointless (pun intended) way of creating a name alias of a pointer. Pretty much the same thing as

int a;
int& ref = a;

But instead *& creates a reference to the pointer itself, rather than at to the data it points at.

Normally one doesn't mix references and pointers in the same context, or at least I can't come up with a sane use-case for this, but it's valid syntax.

  • Related