Ternary if and ~ does not work quite well

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 13 10:45:31 PDT 2015


On Sunday, October 11, 2015 22:21:55 H. S. Teoh via Digitalmars-d-learn wrote:
> It's best to parenthesize when mixing other operators with ?, because ?
> has a pretty low precedence and may "steal" arguments from surrounding
> operators that you don't intend.  My suspicion is that what you wrote is
> being parsed as:
>
>   writeln(("foo " ~ true) ? "bar" : "baz");
>
> which is why you're getting unexpected output. Write instead:
>
>   writeln("foo " ~ (true ? "bar" : "baz"));
>
> If anything, it also helps readers of your code understand what it does
> without needing to consult the precedence table.

The ternary operator is on the next to bottom rung on the same level with
the various assigment operators. The _only_ operator with lower precedence
than the ternary operator is the comma (be it the comma operator or the
comma as an argument separator). So, if you're doing something like

auto i = foo == bar ? "hello" : "world";

or

foo(arg1, foo == bar ? "hello" : "world", arg3);

then the ternary is done before the stuff around it, but other than that,
everything around it is going to be done first. So, whether you need parens
are not is actually pretty straightforward. It pretty much boils down to if
you want the ternary to be done before anything else around it, use parens.
If you want the ternary operator to be done last, then you don't need them.

I actually think that the ternary operator is very easy to get right because
it's pretty much at one end of the operator precedence table rather than in
the middle where you have to remember what goes before and what comes after.
But for some reason, a lot of folks seem to assume that it has different
precedence than it has and have trouble with it.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list