Ternary if and ~ does not work quite well

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Oct 11 22:21:55 PDT 2015


On Mon, Oct 12, 2015 at 05:19:38AM +0000, Andre via Digitalmars-d-learn wrote:
> Hi,
> 
> I am not sure, whether the output of following coding is correct:
> 
> import std.stdio;
> 
> void main()
> {
> 	writeln("foo "~ true ? "bar" : "baz");
> 	writeln("foo "~ false ? "bar" : "baz");
> 	// assert("foo "~ true ? "bar" : "baz" == "foo bar"); does not compile
> }
[...]

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.


T

-- 
EMACS = Extremely Massive And Cumbersome System


More information about the Digitalmars-d-learn mailing list