that is bug?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Apr 7 09:56:43 UTC 2018


On Saturday, April 07, 2018 09:07:48 sdvcn via Digitalmars-d wrote:
>   string stt = "none";
>   true?writeln("AA"):writeln("BB");   ///Out:AA
>          true?stt="AA":stt="BB";    <<<<-----///Out:BB
>   writeln(stt);

Assignment takes precendence over the ternary operator. So, no, I don't
think that it is. Putting parens around the assignment expressions makes it
print AA. As it stands, it evaluates both assignment expressions before
evaluating the ternary operator.

In general, I'd advise against using expressions with side effects in the
branches of a ternary operator, since it's easy to end up with a result that
doesn't do what you think it does (or which readers of your code will
misinterpret) - or you can just always use parens, but the folks who do that
generally end up using parens when they're completely unnecessary, which
IMHO makes the code uglier and harder to read. Either way, if you're doing
assignment, it generally makes more sense to put it outside the ternary
operator. e.g.

stt = condition ? "AA" : "BB";

Also FYI, questions should generally be asked in the D.Learn newsgroup/forum
instead of the main newsgroup/forum, which is for more general discussions
on D and how to improve it.

- Jonathan M Davis



More information about the Digitalmars-d mailing list