Mutability issue

Nick Treleaven nick at geany.org
Sat Mar 23 20:49:14 UTC 2024


On Saturday, 23 March 2024 at 19:30:29 UTC, Menjanahary R. R. 
wrote:
>     for (T candidate = T(5); candidate * candidate <= n; 
> candidate += T(6)) {

When T is `const int`, the above code declares and initializes a 
constant variable:
```d
const int candidate = const int(5);
```

Then, at the end of each loop iteration, it does:
```d
candidate += const int(6);
```

So you are trying to modify a constant. Constants can only be 
initialized, never assigned.

>     T candidate = (n % T(2) == T(0)) ? n + T(1) : n + T(2); // 
> Start from next Odd
>
>     for (;; candidate += T(2)) { // Skip even

Same here, you declare a constant then try to assign to it at the 
end of each loop iteration.


More information about the Digitalmars-d-learn mailing list