Maybe we don't need foreach ;-)

Lionello Lunesu lionello at lunesu.remove.com
Mon Oct 30 22:43:27 PST 2006


I got so used to foreach in D, I've just ported it to C ;)

namespace D {
template <typename T, int S>
inline size_t length( T (&a)[S] ) { return S; }
// Add overloads for your own containers
}

#define foreach(ELEMENT,ARRAY) \
  for(size_t __L=D::length(ARRAY),__B=0,__I=0; !__B && __I<__L; 
assert(__L==D::length(ARRAY)), ++__I ) \
    if (__B = 1) \
      for(ELEMENT = ARRAY[__I]; __B; __B=0) // a break must make the main 
loop stop

Don't get too scared; Microsoft's compiler does a great job optimizing that 
loop. In fact, if you don't use 'break', the second loop will disappear 
completely. I haven't checked the generated code on other compilers yet.

You use it like this (yes, it's C):

int nums[] = {1,2,3,4};
foreach(int i,nums) { }
foreach(int &i,nums) { i=2; }

L.





More information about the Digitalmars-d mailing list