mbeddr.core icon indicating copy to clipboard operation
mbeddr.core copied to clipboard

Wrong translation of for in loop when using negative counts

Open stephaneberle9 opened this issue 11 years ago • 4 comments

E.g.:

for (i -- in [0..-262144]) { ... } for

should translate to

for ( int32_t __i = 0; __i >= -262144; __i-- ) ¨ { ... }

but actually results in

for ( int32_t __i = -262144; __i >= 0; __i-- ) { ... }

stephaneberle9 avatar Jul 12 '13 17:07 stephaneberle9

If you write a --, then the code generator always puts the upper bound as the starting value for the loop.

From my opinion, it makes sense to always (in the '++' and '--' case) use the lower bound as starting value and iterate to the upper bound.

DomenikP avatar Jul 15 '13 19:07 DomenikP

If you write a --, then the code generator always puts the upper bound as the starting value for the loop.

That's absolutely not what one would expect intuitively. When I type -- then I do want the the iteration is counted down but not up.

stephaneberle9 avatar Jul 16 '13 10:07 stephaneberle9

The problem is if the values are not statically known. What do you do then? It is hard to detect the correct behavior there.

bkolb avatar Jul 16 '13 19:07 bkolb

I wouldn't expect the for loop statement to do any magic. If you write a traditional for loop with expressions that evaluate to nonsense kind of boundaries like this

for ( int32_t __i = 1; __i >= 10; __i-- ) ¨ { ... }

then it's also the programmer's own fault and he cannot expect to be "saved" by the C compiler.

stephaneberle9 avatar Jul 16 '13 19:07 stephaneberle9