Parenthesis around if/for/while condition is not necessary

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Jun 23 02:14:04 UTC 2018


On Saturday, June 23, 2018 01:27:30 aedt via Digitalmars-d wrote:
> for line in stdin.lines() {}
>
> if condition {}
>
> while condition {}
>
> for init; condition; op {}
>
>
> What's the rationale of keeping the requirement that the
> condition of if/for/while must be wrapped with a parenthesis
> (other than keeping parser simple)? Modern languages have already
> dropped this requirement (i.e. Rust, Nim) and I don't see any
> reason not to do so.

I expect that it's in keeping with why D also has semicolons. The added
redundancy and separation between statements makes it easier for the
compiler to give intelligent error messages and makes it easier for the
reader of the code to see what's going on. This is particularly true for
parens when you consider that single statement bodies without braces are
allowed for if statements and loops. Not having parens in such cases would
be akin to not having a semicolon at the end of a statement, and in the case
of the for loop, it actually creates an ambiguity problem. When does the
statement in the third portion end and the statement in the body begin?

Another consideration is that it's an unnecessary difference from C/C++
code. 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.

Ultimately, by having these delimiters, the intent of the code tends to be
clearer when mistakes are made, and the compiler can give better error
messages, because it's easier for the compiler to accurately guess what the
programmer intended.

Yes, on some level, it's a subjective design decision, but it's also not at
all the true that programmers in general are going to agree that removing
stuff like parens or semicolons from the language is a good idea. Some will
and some won't. And D follows very much in the tradition of C and C++ with
decisions like this. Syntax was changed from those languages when the syntax
actually caused problems (e.g. C function pointers tend to be problematic,
so D has a different syntax for them), but if the C/C++ syntax was not
considered to be a problem, it was largely left as-is in D. That makes code
porting easier, and it makes it easier for programmers to transition to the
language.

- Jonathan M Davis



More information about the Digitalmars-d mailing list