| |
 | Posted by H. S. Teoh in reply to Paul Backus | Permalink Reply |
|
H. S. Teoh 
Posted in reply to Paul Backus
| On Sat, Nov 27, 2021 at 03:41:05AM +0000, Paul Backus via Digitalmars-d wrote: [...]
> For example, here's a really common error that beginning D programmers make:
>
> ```d
> struct S
> {
> private int[] a;
> const int[] getArray() const { return a; }
> }
> ```
>
> If you try to compile this code, you get the following error:
>
> ```
> Error: redundant attribute `const`
> ```
>
> The reason for this is that in the above code, *both* instances of `const` are treated as applying to the `this` reference, not to the return value. The fix is to add `()` to the first `const`:
[...]
IMO, const as a type qualifier should *always* be used with parentheses. Things like `const int` are a code smell, and an invitation to trouble like the above. This is D, not C, so we should be writing things the D way, i.e., `const(int)` instead of `const int` like we do in C/C++.
Another case is the subtle but important difference between `const(X)[]` and `const(X[])`. When you write `const X[]` it's not immediately obvious which one you get. This is also a cause of stumbling for D beginners.
Therefore, IMNSHO it's a misfeature that the D compiler accepts `const int`. It should reject such cases and always require parentheses, then there would be no ambiguity. Had parentheses been mandatory from the beginning, people would have learned to write const(X)[] and const(X[]) unambiguously, and this would not have been a problem at all. Optional parentheses is a source of needless trouble.
Ditto with immutable, inout, and any other type constructor.
T
--
A mathematician learns more and more about less and less, until he knows everything about nothing; whereas a philospher learns less and less about more and more, until he knows nothing about everything.
|