July 25, 2013 Re: Auto keyword with const variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Alex H | On Wednesday, July 24, 2013 10:07:54 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.
The behavior is correct and desirable. It would be a big problem for generic code if the type of auto didn't match the right-hand side of the expression. In some cases, it might be okay if auto gave you the tail-const type, but even that could be problematic depending on the type.
- Jonathan M Davis
|
July 25, 2013 Re: Auto keyword with const variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mike Parker | On Wednesday, 24 July 2013 at 11:26:32 UTC, Mike Parker wrote:
...
> 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;
+1
This works fine for pods, no cast required
int j = n; ++j;
...and this does what one would expect too
struct S {
int* value;
}
void funky(const S s) {
int* s1 = s.value;
*s1 = 5;
}
/d535/f466.d(9): Error: cannot implicitly convert expression (s.value) of type const(int*) to int*
void funky(const S s) {
S s1 = s;
*s1.value = 5;
}
/d297/f947.d(9): Error: cannot implicitly convert expression (s) of type const(S) to S
|
July 25, 2013 Re: Auto keyword with const variable | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mike Parker | On Wednesday, 24 July 2013 at 11:26:32 UTC, Mike Parker wrote:
> 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;
Casting is always an extreme measure, one that should be avoided in mundane code as much as possible. Despite the fact `auto` behaves as it should, this really highlights lack of `mutable` attribute in language.
|
Copyright © 1999-2021 by the D Language Foundation