Meaning of const

Timon Gehr timon.gehr at gmx.ch
Wed Jan 25 16:02:40 PST 2012


On 01/26/2012 12:35 AM, H. S. Teoh wrote:
> On Wed, Jan 25, 2012 at 11:50:57PM +0100, Timon Gehr wrote:
>> On 01/25/2012 02:29 AM, H. S. Teoh wrote:
> [...]
>>> But since Walter doesn't like the idea of restricting the syntax to 'int
>>> y() const', then what about making it mandatory to write:
>>>
>>> 	const(int) x;
>>>
>>> instead of:
>>>
>>> 	const int x;
>>>
>>> ?
>>
>> You essentially propose to remove the const/immutable/shared/inout
>> storage classes for variables. It would break almost every D program
>> and I don't see many benefits.
> [...]
>> It is very simple. What may be confusing you is that
>> const/immutable/shared/inout are both type constructors and storage
>> classes.
> [...]
>
> Ah, I see. This is very helpful.
>
> So what's the difference between a const int type, and an int variable
> with const storage class?
>
> I think this is the key issue. The syntax makes this distinction
> non-obvious, IMHO, which is very confusing.

The syntax is clear on it: If it is followed by parentheses, it is a 
type constructor. Otherwise it is a storage class.

> This ambiguity also shows up
> in function definitions (allowing storage classes to appear left or
> right of the function name/parameters), which we discussed earlier. From
> what I can tell, Walter doesn't want to change this, but I have to say
> that this is one part of D I find unnecessarily confusing.
>

For variables, the storage class just implies that the type will be 
wrapped in the respective type constructor. The storage class still 
'talks' about the whole declaration though.
A key application is for type deduction:

immutable a = foo();

Foo may return something mutable, and a will automatically have it's 
type deduced to the respective immutable type.

Storage classes always apply to the whole declaration they refer to. It 
is _not_

const int            x;

and

const int          foo;

but:

const            int x;

and

const      int foo(){}








More information about the Digitalmars-d-learn mailing list