Is there any real reason to use "const"?

Steven Schveighoffer schveiguy at gmail.com
Mon Jan 24 19:15:42 UTC 2022


On 1/24/22 11:41 AM, rempas wrote:
> On Monday, 24 January 2022 at 15:40:56 UTC, Walter Bright wrote:
>> Not sure what you mean. This compiles:
>>
>>   int foo(const int);
>>
>>   int bar(int i)
>>   {
>>     return foo(i);
>>   }
> 
> Actually this compiles but what I thought that didn't was something like 
> this:
> 
> ```
> void mul_num(int num) {
>    num *= 2;
> }
> 
> void main() {
>    const int number = 10;
>    mul_num(number);
> }
> 
> ```
> 
> But it turns out that it compiles but I would swear that I tried 
> something similar to this and it wouldn't compile on both D and C.

I know exactly what you were doing:

```d
void mul_num(T)(T num) {
    num *= 2;
}
```

That will fail if you just do `mul_num(number)` because templates infer 
the type from the argument (e.g. T becomes `const int`)

Unfortunately, D doesn't have a "tail-const" modifier, which would work 
really well here.

-Steve


More information about the Digitalmars-d mailing list