|
|
Flash Gordon wrote:
> Bartc wrote, On 31/03/08 18:45:
>> "Richard" <devr_@xxxxxxxxx> wrote in message
>> news:fsr52k$1id$1@xxxxxxxxxxxxxxxxxxxxxxxxxxxx
>>
>>>> Exactly why a?b:c can't appear like that on the left-hand-side of
>>>> an assignment is a bit of a mystery;
>>> There is no mystery about it.
>>>
>>>> after all a, a.b, a->b, a[b] and so on can
>>>> all appear on the lhs without the programmer having to insert
>>>> explicit address-of operators.
>>> And that has to do with ?: how?
>>
>> a: You can write a = x without writing *(&a) = x
>
> You can't do 3 = x
That's true. But when a is a variable, it can appear on the lhs without any
special syntax.
>> a.b: You can write a.b = x without writing *(&a + offsetof b) = x
>
> You can't do 5.b or a.5
Then it won't work on the rhs either.
>
>> (I think offsetof is more complex than that)
>> a->b: You can write a->b = x without writing *(&a + offsetof b) = x
>
> You can't do 5->b or b->5
Nor this.
>
>> a[b]: You can write a[b] = x without writing *(a+b) = x
>
> Unless b is a pointer or array name you can't do 5[b]
>
>> a?b:c: You CAN'T write a?b:c = x without writing *(a ? &b : &c) = x
>
> You can do a?1:2
On rhs yes. On lhs? I don't think so.
>> So the mystery is why the compiler gives special dispensation to
>> those other forms when an lvalue is expected, but not the ?: form.
>>
>> Someone will say, for the same reason as a+b can't usually be an
>> lvalue, but I think ?: is a little different.
>
> I think you are wrong. Look at the fact that all of the other
> operators you mention *require* at least one of the operands to be an
> object but neither + nor ?: require and operand to be an object. Then
> you should see why it is natural for a?b:c = x to be wrong.
That's true. And probably the reason it was disallowed in C.
But when both selections of ?: /are/ legal lvalues there doesn't seem to be
a particular problem. After all the lhs of an assigment must be an lvalue,
so why not insist on both values of an ?: on the lhs being lvalues?
For example if someone tries to write:
a ? b : c+d = x;
then clearly there's an error. But that's no different from the equally
incorrect:
if (a)
b = x;
else
c+d = x;
I suppose I should put my cards on the table here: I have written compilers
for C-class languages where such an expression on lhs of an assignment is
valid (in fact anything can appear on the lhs provided it yields an lvalue).
So the following nested ?: operation is possible:
(a | b | (c | d | e)) := 100 /* syntax is (a|b|c) not a?b:c */
This assigns 100 to either b, d or e depending on a and c. Not that such a
construct, even the simpler a?b:c form, is used that often! :-)
But it's clearly controversial in C.
--
Bart
|
|