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.

  1. foreach iterate on practically anything (even metadata, compile-time data types); for can't.

    foreach (type; typetuple!(int, long, short)) { pragma(msg, type); } 

    but can't for loop.

  2. foreach can 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, i treated constant. (this doesn't work for.)

  3. foreach can overloaded opapply , range constructs, for can'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).

  4. foreach preferred in situations because prevents need type data explicitly, useful in preventing bugs. example,

    for (int = 0; < n; i++) { arr[i]++; } 

    is dangerous if n greater 2^32 - 1, but

    foreach (i; 0 .. n) { arr[i]++; } 

    is not, because compiler automatically chooses correct type iteration. improves readability.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -