const in functions

Ali Çehreli acehreli at yahoo.com
Sun Mar 12 19:09:13 UTC 2023


On 3/12/23 08:09, Salih Dincer wrote:

 > As someone who has used const very little in my life

You can live without 'const' until your code interacts with other 
people's code. For example, the following program works just fine:

struct S {
     int * p;

     void foo() {}
}

void bar(S s) {}

void main() {
     auto s = S();
     s.foo();
     bar(s);
}

Now you replace (or a user of your code replaces) 'auto' with 'const' 
and you will get 2 compilation errors:

     const s = S();
     s.foo();        // ERROR 1
     bar(s);         // ERROR 2

So, if your code will ever interact with other people's code it must be 
const-correct. If foo() is not mutating the object (including through 
the p member), it better be defined as 'const':

     void foo() const {}

And if bar() is not mutating the parameter, it better take as const:

void bar(const(S) s) {}

Now the code compiles.

You can (and should) use 'const' everywhere that you can because it 
increases the usability of code: Mutable, 'const', and 'immutable' 
variables can be used with code that takes by 'const'.

This is not the same with code taking by 'immutable'. It can only be 
used with 'immutable' variables.

Ali



More information about the Digitalmars-d-learn mailing list