jack: (Default)
[personal profile] jack
In many "introduction to C-style programming language" books, you see two variables being set to the same value with syntax like:

 x = y = 0


In fact, I almost never write that in real life. Normally I find:

* The variables are being declared and initialised, and you can't write "int a = int b = 0"
* It's possible the variables may be set to different values under some circumstances, in which case I find assigning them in separate statements clearer.
* It's being done to squeeze an extra statement into a conditional expression, like "while (p=getcharacter()) { dosomething(p) }", and it's actually clearer to move the assignment to a separate line

All the same, if I've ever declared any assignment operators on any user defined classes, I've always scrupulously declared them to return the value used*.

But for the first time in about five years, I actually *did* try to write "if (newval>obj.max) obj.val = obj.max = newval".

And it failed. Because obj was from the .NET framework, which has getters and setters, and setters apparently do NOT return a value. I'm not sure if they _should_. But maybe this piece of advice is dead now, if I never needed it before?

* Aside

In the C++ books I've seen, in fact they return a non-const reference from their assignment operators, allowing you to write:

(obj=1)=2


I assume no-one ever WOULD want to write that, because either (a) the assignment has no side effects, and it's pointless or (b) "obj=1" does something interesting, when it should have its own line. Why is the reference non-const, is it so it so that you can write "a = (obj=1)" or "f( obj=1 )" even if a.operator= or f take non-const parameters?

Date: 2009-12-09 10:37 pm (UTC)
andrewducker: (Default)
From: [personal profile] andrewducker
Could be the way C++ interacts with it.

And I can see positives to breaking it up or leaving it one line, depending on how lazy I'm feeling :->