Reputation:
"lvalue-to-rvalue conversion is not done on the operand of the unary & operator."
May I know what it meant for >Can any one explain ..It Please
Ex:
int a[]={1,5};
int* x=&a;
Upvotes: 1
Views: 906
Reputation: 209
Well, it means that the lvalue to rvalue conversion isn't done:-). An lvalue to rvalue conversion occurs when you need the value of an object, rather than just a reference to it. Taking the address of an object doesn't require the value, so there is no lvalue to rvalue conversion.
I'm not sure how this is relevant to your code. The conversion which isn't being done in the second line in your code is the array to pointer conversion. The lvalue to rvalue conversion isn't being done either, of course, but that's rather intuitive and normal. The array to pointer conversion occurs in most uses of an array in an expression, however, and so might surprise some people more. (Actually, the array to pointer conversion only occurs when necessary. But there are very, very few operations which are legal on an array, so it's very often necessary.) In the case of a unary & operator, the array to pointer conversion doesn't take place (and can't, since the result of the array to pointer conversion is an rvalue, and unary & requires an lvalue). So you're taking the address of the array, which has type int ()[2], i.e. pointer to an array of two int. Which in turn makes the assignment illegal, since the target type is not int ()[2], but int*, and there's no implicit conversion between the two.
Upvotes: 3
Reputation: 263350
int a[] = {1, 5}; int* x = &a;
That's a type error. The &
operator yields a pointer to its operand. What's its operand here? An array of 2 integers. A pointer to an array of 2 integers is not of type int*
, but of type int(*)[2]
.
Note how the rule you quoted applies here: in many contexts, the name of an array decays to a pointer to its first element. (But generally, arrays and pointers are not the same!) That's what happens when you say int* x = a;
. But this decay does not happen when you apply the &
operator to an array. (If that conversion did happen, &a
would try to take the address of the address of a
, which is nonsense.)
Upvotes: 1
Reputation: 793199
In an expression, an lvalue to rvalue conversion refers to looking at the value of an object and is used where you need an object value (e.g. in a + b
you need the values of a
and b
to determine the result you don't need to know where - if anywhere - the original objects came from).
In the address-of operator you need to have the object itself (i.e. an lvalue), the value of the object is irrelevant so an lvalue to rvalue conversion would be unhelpful, it would lose the identity (location) of the object itself which is what is important for taking an address.
Upvotes: 1