2
votes
#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:

  1. a variable where the type is different but can be converted.
  2. a variable that is not a Lvalue.

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 .

Case 1
#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.

1
Please, please see my edit before you post another question. You should learn to use the markdown editor. It is almost never necessary to fall back to using HTML in your posts. Learn markdown and please stop posting brtual html like the following:<i>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; - user229044
And please stop using "THE CODE" and "THE QUESTION" headers. We can tell which parts are the code, and which parts are the question. We rely on the markup and the language in your post to figure out what you're asking, littering bold headers around just clutters things. - user229044

1 Answers

4
votes

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.