Reputation: 3055
#include <iostream>
using namespace std;
int main(void)
{
int num[5];
const int* &ref = num;
return 0;
}
I've read a C++ book which mentioned if a reference variable is referencing to:
As long as the referencing variable is declare as const
, the above 2 cases will be solved by using a method where the compiler will create a storage and the value will be placed into it while the identifier of the referencing variable is treated as the identifier for that particular storage location . Below is the demonstration code .
#include <iostream>
using namespace std;
int main(void)
{
int num = 5;
const long long &ref = num; //the value 5 is place in a new storage where ref is the identifier
return 0;
}
Case 2:
#include <iostream>
using namespace std;
int main(void)
{
int num = 5;
const int &ref = num + 1; //expression num + 1 evaluated and store in new storage with identifier ref
return 0;
}
Since this 2 cases is valid, how come the case inside The Code: is invalid?
My logic is since the name of the array when used will be converted to pointer to the first element of the array , thus the compiler should've spotted this is not a lvalue and a new storage will be created to store that address along and of course , the referencing variable name will be taken as the identifier for that location .
Note : I know this is slightly out of topic , but may I know whether an array name is Lvalue or not? Just a simple yes or no will do , since changing the code to int &ref = num
I assume it's not a lvalue , but I just need further confirmation.
Thank you.
Upvotes: 2
Views: 744
Reputation: 279315
You reference variable is not declared const.
There's a difference between const int *
and int * const
, and you've picked the wrong one.
Your example (ii) is invalid for the same reason, it should be const int &ref = num + 1;
For your Note, I'm not sure that a simple yes or no will do. A simple array name is an lvalue, referring to the array. However, in most contexts it decays to a pointer-to-first-element, which is an rvalue pointer.
Upvotes: 4