InsaneCoder
InsaneCoder

Reputation: 8278

References in C++ and its memory requirement

Suppose if I write the following code

int i=10;
int &j=i; //a reference in C++,don't confuse it with pointers & address

Does j takes any space in the memory as its simply a reference?

Upvotes: 0

Views: 152

Answers (3)

0decimal0
0decimal0

Reputation: 3984

First of all you are doing invalid initialization of &j as said by Luchian.

A reference is just a name given to the variable's memory location.You can access the contents of the variable through either the original variable name or the reference. You can read the following declaration :

int &j=i;

as:

j is an integer reference initialized to i.

Well, their occupying space is implementation dependent,Its not that they are stored somewhere, you can think of them just as a label.

From C++ Standard (§ 8.3.2 #4)

It is unspecified whether or not a reference requires storage

The emphasis is mine.

*NOTE--*References are usually used for function argument lists and function return values.

Upvotes: 0

Subhajit
Subhajit

Reputation: 320

Error when you try to assign the reference to a constant value "error C2440: 'initializing' : cannot convert from 'const int' to 'int &'"

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

You can't bind a non-const reference to a const value. The compiler should give you an error:

invalid initialization of reference of type ‘int&’ from expression of type ‘const int’

Even if you do get around this (with, for example, a const_cast), the code will have undefined behavior because you're modifying an originally const value.

Does i takes any space in the memory as its simply a reference?

That's an implementation detail - it could be optimized out completely. What you need to know is that j is just a nickname for i.

Upvotes: 3

Related Questions