June 25, 2010Question about the validness of code examples in the docs
Hi, I'm doing a review of the language reference documentation. What I've noticed in a lot of the example code is that it is not syntactically correct. Sometimes, this is wanted behavior. For example, take this Array Length code example: int foo; int bar = foo; int* p = &foo; // These expressions are equivalent: bar bar[0 .. 4] bar[0 .. $] bar[0 .. bar.length] p[0 .. $] // '$' is not defined, since p is not an array bar+$ // '$' is not defined, out of scope of [ ] bar[$-1] // retrieves last element of the array The goal of this example is to show that the dollar symbol is not available for pointers, or when it is outside the scope of the array. So the example should not compile. The above code won't compile, which was expected, but it won't compile for a number of different reasons: (1) Statement terminators are missing, (2) The expressions have no effect, "array;" doesn't mean anything to the compiler and it will complain about it, and finally (3) $ is undefined in those two expressions, just like noted in the comments This is a trivial example, but other examples have even worse broken syntax. In one code example taken from the docs, I got this little monster of an error message: foreach_test.d(38): Error: function object.AssociativeArray!(const(char),double).AssociativeArray.opApply (scope int delegate(ref const(char), ref double) dg) is not callable using argument types (int delegate(ref double __applyArg0, ref char __applyArg1)) foreach_test.d(38): Error: cannot implicitly convert expression (__foreachbody524) of type int delegate(ref double __applyArg0, ref char __applyArg1) to int delegate(ref double) With all of that said, the above Array Length example would then possibly look like this instead: int foo; int bar = foo; int* p = &foo; // These expressions are equivalent: writeln( bar ); writeln( bar[0 .. 4] ); writeln( bar[0 .. $] ); writeln( bar[0 .. bar.length] ); writeln( p[0 .. $] ); // '$' is not defined, since p is not an array writeln( bar+$ ); // '$' is not defined, out of scope of [ ] writeln( bar[$-1] ); // retrieves last element of the array Now the compiler would only complain about the undefined dollar sign, which is what the code example was trying to show in the first place. My question to Walter/Andrei and the community is, would you rather see compilable examples which show you the same errors (if any) as noted in the code comments, or leave the code examples as they were?
Copyright © 1999-2017 by the D Language Foundation