Why isn't ++x an lvalue in D?

Don nospam at nospam.com
Fri Jan 9 00:21:40 PST 2009


Weed wrote:
> Bill Baxter пишет:
>> On Fri, Jan 9, 2009 at 2:43 PM, Weed <resume755 at mail.ru> wrote:
>>> Weed пишет:
>>>> Bill Baxter пишет:
>>>>> 2009/1/9 Weed <resume755 at mail.ru>:
>>>>>> Bill Baxter пишет:
>>>>>>> Another thread just reminded me of something I use frequently in C++
>>>>>>> that doesn't work in D because ++x is not an lvalue:
>>>>>>>
>>>>>>>    int x,N;
>>>>>>>   ...
>>>>>>>    ++x %= N;
>>>>>>>
>>>>>>> So is there some deep reason for not making it an lvalue like in C++?
>>>>>>>
>>>>>> ++x is x+=1 in D:
>>>>>>
>>>>>> void main() {
>>>>>>  int i =3;
>>>>>>  int N =2;
>>>>>>  (i+=1) %= N;
>>>>>> }
>>>>>>
>>>>>>
>>>>>> Error: i += 1 is not an lvalue.
>>>>>>
>>>>>> C++:
>>>>>>
>>>>>> int main()
>>>>>> {
>>>>>>  int i = 2;
>>>>>>  int N = 3;
>>>>>>  i+1 %= N;
>>>>>>
>>>>>>  return 0;
>>>>>> }
>>>>>>
>>>>>> error: lvalue required as left operand of assignment
>>>>>>
>>>>> What does C++ do if you use  (i+=1) %= N instead of (i+1)?  Doesn't +=
>>>>> also return an lvalue in C++?
>>>> I am a bit mixed, but the meaning has not changed:
>>>>
>>>> $ cat demo.cpp
>>>> int main()
>>>> {
>>>>  int i = 2;
>>>>  int N = 3;
>>>>  i+=1 %= N;
>>>>
>>>>  return 0;
>>>> }
>>>>
>>>> $ c++ demo.cpp
>>>> demo.cpp: In function 'int main()':
>>>> demo.cpp:5: error: lvalue required as left operand of assignment
>>> And I think it is wrong that the ++ same as += 1. The operator ++ in C
>>> uniquely compiles in CPU instruction "increment".
>>>
>>> For objects it would be better to make a += 1 only if undefined
>>> overloaded operator ++.
>> Yeh, I think that's scheduled to be changed after Andrei's repeated
>> thrashings of Walter.
> 
> Thus, once it works it is necessary to change anything if only for the
> real types increment will give increase for the lowest possible value.
> (I do not know how the CPU instruction increment works for real values)

There is none. In tango.math.Math there's nextFloatUp, nextDoubleUp, 
nextRealUp, which perform the "next possible number" operation.
In D, ++x for real x performs x = x + 1.0.
If x is (say) 1e80, then (++x) == x !

I'm not sure why D allows ++x for floating-point types, it's asking for 
trouble IMHO -- if you're incrementing a real, I think it's highly 
probable that you have a bug somewhere.



More information about the Digitalmars-d mailing list