Should I prefer immutable or const?

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Nov 1 11:54:36 PDT 2016


On 11/01/2016 06:52 PM, Nordlöw wrote:
> Should I always, when possible, prefer `immutable` over `const`?

I'd say: prefer immutable.

> And does `immutable` increase the possibility of the compiler doing
> optimizations, such as common subexpression elimination?
>
> Or can the compiler infer `const` declarations to also be `immutable`?

A `const int x = 42;` is effectively immutable, but its type is 
const(int), not immutable(int). A compiler may be smart enough to treat 
it as immutable with regards to optimizations, but I wouldn't expect dmd 
to be that smart, or only in very simple cases. ldc and gdc are probably 
better at it.

However, for function overloads and such the compiler must consider the 
type, not any additional information it has about the data. So if some 
function has an optimized overload for immutable, that can only be taken 
when you type out "immutable".


More information about the Digitalmars-d-learn mailing list