Auto keyword with const variable

Mike Parker aldacron at gmail.com
Wed Jul 24 04:26:31 PDT 2013


On Wednesday, 24 July 2013 at 08:07:55 UTC, Alex H wrote:
> This code:
>
> void test(const int n)
> {
> 	auto j = n;
> 	j++;
> }
>
> Gives this error:
> cannot modify const expression j
>
>
> Is this considered a feature or a bug? I would assume most 
> people
> wouldn't want new variables inheriting const.

This is the exact behavior I would expect. I think of auto as 
"this variable is going to be the same type as that variable." 
Since in is const int, then j also is going to be const int. If 
you want to copy n into a nonconst variable, you have to cast 
away the const.

int j = cast( int )n;
auto j = cast( int )n;


More information about the Digitalmars-d-learn mailing list