What am I missin with const?

Nick Treleaven ntrel-public at yahoo.co.uk
Wed Jan 30 10:03:15 PST 2013


On 29/01/2013 10:21, Era Scarecrow wrote:
> On Tuesday, 29 January 2013 at 09:45:17 UTC, Timon Gehr wrote:
>> On 01/29/2013 10:38 AM, deadalnix wrote:
>>> Well I think the error message you propose isn't possible as it would
>>> cause many problems in generic code.
>>
>> How?
>>
>>> const applied to the return type should be the way to go. It is
>>> basically what everybody except at first when looking at the code.
>>> But it is probably too late to change that.
>>
>> The current behavior emerges because the parser treats
>>
>> const void foo(){}
>>
>> exactly like
>>
>> const{
>>     void foo(){}
>> }
>
>   Somehow that's what I'd prefer, Consistency. If it's an int, then
> these two could be very confusing based on location of const. So if
> const is unattached it is for the whole function
>
>   const int foo() //misleading
>   vs
>   int foo() const
>
>   However specifying an item that's const will always result in the
> correct const of that type. There's never ambiguity following those
> rules; Although those coming from C++ will need to put the extra effort
> to specify which is const.
>
>   const(int) foo()
>   vs
>   int foo() const

There is unnecessary syntactic ambiguity for users unaware of the 
problem (or aware users that are tired so not able to recognize the 
problem immediately). This is exactly the same reason dmd warns about a 
dangling else:

     if (x)
         if (y){}
         else {}	// warning: dangling else

The above is consistent and correct code from the compiler's point of 
view, but is bug-prone for humans, so the compiler complains. The fact 
it comes up in the newsgroups periodically is proof the current syntax 
is confusing.


More information about the Digitalmars-d mailing list