Where does the reference variable gets stored

That is left unspecified, and for good reason. The real answer is: it depends on the reference. It can be represented as a normal pointer, or it may not exist at all.

If you have a function-local reference with automatic storage duration, such as this r:

void foo()
{
  int x[4] = {0, 1, 2, 3};
  int &r = x[1];
  // more code
}

then it will probably not take up any space at all. The compiler will simply treat all uses of r as an alias for x[1], and access that int directly. Notice that such alias-style references can also result from function inlining.

On the other hand, if the reference is "persistent" or visible to other translation units (such as a data member or a global variable), it has to occupy some space and be stored somewhere. In that case, it will most likely be represented as a pointer, and code using it will be compiled to dereference that pointer.

Theoretically, other options would also be possible (such as a lookup table), but I don't think those are used by any real-world compiler.


I know that reference does not take any memory

Not exactly. Whether a reference has storage, is unspecified. It might or it might not. In this particular example, it does not need storage, so in a typical implementation, it doesn't use any.

it's will point to the same memory location which it is referencing

That sounds like a tautology or simply a misunderstanding, depending on what you mean by "point". A reference refers to the object or is bound to the object. You can consider it an alias of the variable name. The variable name doesn't use any memory either.

In this case r is pointing to some location but it should be stored somewhere in memory

It doesn't need to be stored in memory. Consider following code:

int i=10;
int &r = a;
int j = r * 3;

The compiler can interpret r * 3 as i * 3 as if you had written so in the first place. The location of the referred object is known at compile time, so there is no need to store the address in memory which is a run time thing.

But, in other situations, storage may be needed. For example: Consider a reference argument of a non-inline function that has external linkage. The referred object cannot be known when the function is compiled, so some information must be passed along in memory, at run time.

as internal representation on reference use const pointer only

That's not correct. The internal representation might use a pointer, or it might use something else, or it might not need to use anything.

So, to concisely answer

Where does the reference variable gets stored

It is unspecified. Either nowhere, or somewhere.

Tags:

C++

Memory