0

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?

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
Naveen
  • 7,944
  • 12
  • 78
  • 165
  • 2
    `int &j=i;` is invalid conversion. – billz Jul 25 '13 at 09:15
  • @AmoghDikshit THen explain why, the OP clearly doesn't understand his mistake. – jwbensley Jul 25 '13 at 09:18
  • The `j` is a reference ,if you are confusing it with pointers. – Naveen Jul 25 '13 at 09:18
  • 1
    Don't you feel this is wrong from your output 10 20 that its not possible. if j is reference which points to i so when you change j's value to 20 which is actually points to i then both's value should have to be 20 according to concept but that's not happening. Read about reference in detail. – Hitesh Vaghani Jul 25 '13 at 09:22
  • int &j=i; conversion not possible – Subhajit Jul 25 '13 at 09:24
  • First you are using reference to a `CONST` For the answer of your question in the first place, You should take a look here http://stackoverflow.com/questions/1179937/how-does-a-c-reference-look-memory-wise –  Jul 25 '13 at 09:30
  • OK Thanks for making me correct,actually the book correct.That was the mistake of author.Please see the edited question – Naveen Jul 25 '13 at 09:31

3 Answers3

3

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

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

Subhajit
  • 320
  • 1
  • 6
0

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.

0decimal0
  • 3,884
  • 2
  • 24
  • 39