Reputation: 55
compiler says invalid initialization at line 3 I guess creating reference to i, it is telling the compiler that someone wants to change i, I guess this thing came with newer versions of the compilers because i have found this code in most of the books.
int main(){
const int &i=10;
int &j=1;
cout<<j;
return 0;
}
Upvotes: 0
Views: 914
Reputation: 10613
Besides missing an int
in const &i=10;
the issue with the next line is that you are creating a reference that is not const
(i.e. which allows what it refers to to be changed) and the number 1
is a constant. You'd encounter the same problem with the following code:
const int i = 1;
int &ri = i;
It should be obvious why.
Upvotes: 0
Reputation: 249652
This:
int &j=1;
Is not valid, because you're creating a non-const reference (which would allow you to modify the referent) from a constant value (which cannot be modified, for obvious reasons).
Do this instead:
const int &j=1;
Also, the line that declares i
makes no sense. Just delete it.
Upvotes: 2