Parenthesis around if/for/while condition is not necessary

Dennis dkorpel at gmail.com
Sun Jun 24 22:03:13 UTC 2018


On Saturday, 23 June 2018 at 02:14:04 UTC, Jonathan M Davis wrote:
> In general, C code is supposed to be either valid D code or not 
> compile in order to making porting it easier. Getting rid of 
> the parens wouldn't break that, but it _would_ make it so that 
> it's more work to port C code to D when doing so is supposed to 
> be straightforward in most cases.
>
> And of course, the counter question to why the parens shouldn't 
> be removed would be the question of why they should be. What 
> about having parens makes the code worse? Many of us would 
> consider the code easier to read with parens.

I don't see why allowing one to omit the parens makes porting C 
code harder. The fact that D allows `printf = "hello world";` 
doesn't mean you have to write it like that, you can still use 
the C notation. The same applies to parens.

I would be in favor for allowing this. It's not that I encourage 
omitting them, it's similar to curly braces around the statement: 
You want them most of the time, but in certain scenarios you like 
to be able to leave them out. In particular:

if (!("key" in dict)) {...}
if (!(flags & 0x40)) {...}

These are annoying to type and read. There are more than 100 
instances of this in the dmd source code. Aren't these just much 
nicer? :)

if !("key" in dict) {...}
if !(flags & 0x40) {...}

It gets worse as expressions get larger. Parens may be easy to 
read around small expressions, but can you tell quickly whether 
the parens below are balanced?

if (!(t1.ty == Tarray && t2.ty == Tarray && needsDirectEq(t1, t2))

How about this one?

if (!(i1 && i2 && (i1.mod == i2.mod || (!i1.parent.isImport() && 
!i2.parent.isImport() && i1.ident.equals(i2.ident)))))

The compiler will easily output 5+ error messages pointing to the 
wrong place when a closing paren is missing ("missing { ... } for 
function literal", "unrecognized declaration"). So I'm not 
convinced that error message quality is at stake here.

To avoid ambiguity of where the expression ends and body starts, 
it can be enforced that either () around the expression or {} 
around the statement must be present.


More information about the Digitalmars-d mailing list