auto declarations
bearophile
bearophileHUGS at lycos.com
Sat Jan 8 03:27:34 PST 2011
Ellery Newcomer:
> int a = 1, *b = null;
Walter has disallowed code like this in D because in C it is a well known source of bugs (so much that C style guides strongly suggest to declare only each variable in a distinct statement and line of code).
> auto a = 1, b = null;
I have discussed this with other people some time ago. At first I don't like this, it's against the D rule of not allowing different types to be initialized in the same statement. It may cause some bugs.
Example: if you write a line of code like, meaning it to initialize six double variables both you have a bug:
auto x1=1., x2=2., x3=3., x4=4., x5=5, x6=6.;
But you are playing with fire. Better to be safer and write:
double x1=1., x2=2., x3=3., x4=4., x5=5, x6=6.;
Or even:
double x1, x2, x3, x4, x5, x6;
x1 = 1.0;
x2 = 2.0;
x3 = 3.0;
x4 = 4.0;
x5 = 5.0;
x6 = 6.0;
Or:
double[6] x;
foreach (i, ref xi; x)
xi = i + 1;
Or:
double[6] x = array(iota(1.0, 7.0));
> The first is accepted by dmd, and it should result in typeof(a) == int
> and typeof(b) == void*. It is somewhat contradictory to the error
> message resulting from the second:
>
> multiple declarations must have the same type, not int and int*
Error messages in DMD are a draft :-) I have opened many bug reports that suggest to improve them.
Here the error message is not fully correct, but I think it's acceptable. To improve it the D compiler may also give a number of the error, and a manual of the errors may explain that indeed the "auto" is allowed to instantiate different types, etc. I don't know why DMD errors are not numbered ad in C#.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list