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?

7
  • 2
    int &j=i; is invalid conversion. Commented Jul 25, 2013 at 9:15
  • @AmoghDikshit THen explain why, the OP clearly doesn't understand his mistake. Commented Jul 25, 2013 at 9:18
  • The j is a reference ,if you are confusing it with pointers. Commented Jul 25, 2013 at 9: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. Commented Jul 25, 2013 at 9:22
  • int &j=i; conversion not possible Commented Jul 25, 2013 at 9:24

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Compilers implement references as pointers and thus they do consume space.
@NikosC. Sometimes. As a local variable, I'd be surprised if any compiler allocated memory for the reference.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.