Error: function `...` without `this` cannot be `const`

someone someone at somewhere.com
Wed Jun 30 17:47:05 UTC 2021


I do not understand the compiler error when I add the const 
keyword in the following function which works (and compiles) as 
expected without the const keyword:

```d
public string getAmountSI(
    in float lnumAmount
    ) const {

    /// (1) given amount

    string lstrAmount;

    if (lnumAmount < 1_000f) {

       lstrAmount = r"1K"c;

    } else {

       if (lnumAmount < 1_000_000f) {

          lstrAmount = format(r"%.0fK"c, lnumAmount / 1_000f);

       } else {

          lstrAmount = format(r"%.0fM"c, lnumAmount / 1_000_000f);

       }

    }

    return lstrAmount;

}
```

I used to put all attributes BEFORE the function name which now I 
understand is completely wrong since they should follow the 
parameter declaration section because putting them before affects 
the function in other ways.

I first noted this while browsing the DUB package DB and came 
accross https://code.dlang.org/packages/dscanner which states 
(among a lot of checks):

- Placement of const, immutable, or inout before a function 
return type instead of after the parameters

Is it because const for a function is intended to be used ONLY 
within a structure/class (ie: a method) and thus the this error 
(http://ddili.org/ders/d.en/const_member_functions.html) ?

Can anyone explain please ?

PS: I think I should re-check all the code I've written so far 
for things like this that obviously I quite not completely 
understand yet.



More information about the Digitalmars-d-learn mailing list