const in functions

Ali Çehreli acehreli at yahoo.com
Fri Mar 17 22:41:18 UTC 2023


On 3/12/23 16:14, FozzieBear wrote:
 > On Sunday, 12 March 2023 at 15:09:45 UTC, Salih Dincer wrote:
 >>
 >> ...
 >
 > So I don't agree with part of this comment (made elsewhere in this 
thread):
 >
 > "You can live without 'const' until your code interacts with other
 > people's code."

My comment was purely technical. What I meant is, if the code is an 
island where there is no single 'const' in sight, then a D programmer 
can live by ignoring 'const'. At a technical level...

This is different from C++ where you have to use references to const in 
order to take rvalue references as parameters. Since D does not allow 
binding rvalues even to references to const, this is a moot point. 
(-preview=in does bind rvalues to references as an optimization but that 
fact is hidden from the programmer.)

So, my comment is correct at a technical level.

 > Code interacts with other code. Code should always be clear as to its
 > intent.

Absolutely. That's why I always start with 'const' (what should have 
been the default but is not for historical reasons):

   const foo = bar();

I change that 'const' to e.g. 'auto' as needed.

 > Who wrote that code, or other code that interacts with that
 > code, is irrelvant.

However, there is always the danger of going too far though. To keep the 
fun in the game, a programmer should be free to do whatever they want in 
their own code e.g. in their throw-away script programs.

Here is one line I never include in production code but I very 
frequently use in short programs:

import std;

Removes mental load, frees the mind, and enables flow of programming.

Some code is written for myself, not for people who are not watching 
over my shoulder. There is pride in caring for every character of the 
source code but sometimes freedom from all concerns is good too. 
Luckily, D makes it easy to refactor as requirements change.

Ali



More information about the Digitalmars-d-learn mailing list