Researcher question – what's the point of semicolons and curly braces?

Chris via Digitalmars-d digitalmars-d at puremagic.com
Wed May 4 04:35:05 PDT 2016


On Wednesday, 4 May 2016 at 11:03:46 UTC, cym13 wrote:
> On Wednesday, 4 May 2016 at 09:28:41 UTC, Chris wrote:
>> [1] Consider the following code, which will work correctly:
>>
>> x = 5
>>
>> if x < 6:
>>   print "Checking value"
>>   print "%d is less than 6" % x
>>
>> Now look at this:
>>
>> x = 10
>>
>> if x < 6:
>>   print "Checking value"
>> print "%d is less than 6" % x  # <--- wrong indentation level
>>
>> This will incorrectly print "10 is less than 6". Which gives 
>> causes two problems
>>
>> 1. no compiler or editing tool can see what your intention was
>> 2. the program works, albeit, incorrectly. In bigger programs, 
>> it can take a while to find out why the program is behaving 
>> incorrectly, because up to 5 it always works fine, and if 6-10 
>> is less common, it can take a while until you even notice the 
>> bug.
>>
>> In D (or C) it doesn't matter:
>>
>> if (x < 6)
>> {
>>   writeln("Checking value");
>> writefln("%d is less than 6", x);
>> }
>
> There again I completely disagree with you. The intent in the 
> first braceless sniplet is clearly to have both statements 
> ruled by the condition. Eyes look at indentation before 
> anything else as prove bugs like goto-fail. Ignoring that 
> intent by allowing code to lie with their indentation level 
> like C or D does is more of a mistake IMHO.
>
> if (x < 6)
>     writeln("Checking value");
>     writeln("%d is less than 6", x);
>
> should be at the very least a warning, at best an error.

The intention is clear in _this_ simple example, but only to a 
human reader, not to a tool. My point was that it's easy to have 
an indentation level mistake like this somewhere in your code 
(and please don't tell me it never ever happens to you), and if 
this happens in a huge program somewhere in a file that contains 
a few hundred lines, it's not easy to track it down (or even to 
notice for quite a while).

Although your example compiles in D (it should give at least a 
warning, I agree), this sort of code is not common in D. Anything 
with more than one line is usually put into curly braces, the 
point being that D does neither demand nor encourage the use of 
indentation level to indicate where a block of code starts and 
ends. If a language (like Python) does demand it, it invites you 
to make subtle mistakes. In other words, in D errors like the one 
described in my previous post do not occur (or at least very 
rarely). In Python they are a common source of bugs. And again, I 
strongly believe that formatting code should not be a language 
feature.


More information about the Digitalmars-d mailing list