for and foreach statements in D -
besides syntactic differences, 2 inherently same? both of them implemented in core language? or foreach part of standard library? , far performance, make difference if choose 1 on other?
you should use foreach if possible.
foreachiterate on practically anything (even metadata, compile-time data types);forcan't.foreach (type; typetuple!(int, long, short)) { pragma(msg, type); }but can't
forloop.foreachcan used perform actions @ compile-time (extension of above); example, if have piece of code repeats 10 times, can say:template iota(size_t a, size_t b) //all integers in range [a, b) { static if (a < b) { alias typetuple!(a, iota!(a + 1, b)) iota; } else { alias typetuple!() iota; } } foreach (i; iota!(0, 10)) { int[i] arr; } //not possible 'for'and occur @ compile-time,
itreated constant. (this doesn't workfor.)foreachcan overloadedopapply, range constructs,forcan't. very handy when iterating tree structure (like folders in file system), because allows use entirely stack-based memory rather allocating on heap (because can use recursion).foreachpreferred in situations because prevents need type data explicitly, useful in preventing bugs. example,for (int = 0; < n; i++) { arr[i]++; }is dangerous if
ngreater 2^32 - 1, butforeach (i; 0 .. n) { arr[i]++; }is not, because compiler automatically chooses correct type iteration. improves readability.
Comments
Post a Comment