Maybe we don't need foreach ;-)
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Tue Oct 31 02:35:57 PST 2006
Lionello Lunesu wrote:
> 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
I think you have a dangling-else bug here:
if (whatever)
foreach(elt, arr) { something(); }
else
somethingelse();
What happens in this code? It looks like somethingelse() will be
executed if whatever evaluates to false, but IIRC the 'else' clause will
bind to the 'if' you have in your macro. Since that one never evaluates
to false, somethingelse() will never be called here.
I haven't tried it though, this was just from looking at it.
Also, this won't manifest itself if you always use braces after 'if's so
this may be hard to spot the one time you forget :).
More information about the Digitalmars-d
mailing list