question about conditional operator (?:)

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 26 07:32:49 PDT 2016


On Tuesday, July 26, 2016 13:41:39 Richard via Digitalmars-d-learn wrote:
> On Tuesday, 26 July 2016 at 13:19:54 UTC, ag0aep6g wrote:
> > Operator precedence is different from what you think. `a ? b :
> > c = d` means `(a ? b : c) = d`. But you want `a ? b : (c = d)`.
> > So you need parentheses around `p+=1`.
> >
> > Or just go with `if` and `else`. It's clearer anyway.
>
>  From http://wiki.dlang.org/Operator_precedence
>
> Priority(15 is highest)
> 3                      Conditional operator                  ?:
> 2                      Assignment operators    = -= += <<= >>=
>
>  >>>= = *= %= ^= ^^= ~=
>
> I was actually close to not needing parentheses :). But I see
> that your suggestion to stick with if else in this case is the
> sensible thing to do, especially since ?: seems to lead to more
> errors. Thanks for the answers.

The ternary operator is invaluable for stuff like initializing a constant
based on boolean condition, and it can be useful in code in general, but I
think that most everyone would agree that you don't want to be doing
mutating operations inside of a ternary operator and that if/else statements
are far better suited to that - particularly since the ternary operator
results in a value, which is not at all what you're looking to do here.

That being said, it surprises me how often folks get confused by the
precedence of the ternary operator and start throwing parens around it. The
only reason that you'd need to here is becasue of the assignment operations,
which really shouldn't be used in a ternary expression anyway (except when
using the result of the whole expression as the value to assign).

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list