Shop OBEX P1 Docs P2 Docs Learn Events
When is 0 a -1 - again! — Parallax Forums

When is 0 a -1 - again!

vaclav_salvaclav_sal Posts: 451
edited 2009-02-14 02:00 in BASIC Stamp
This code snippet ends up with BCDIndex = 0
Why?

When tested to 0 BCDIndex = 15.

I am sooo confused....

Clear_BCD:
DEBUG "Clear_BCD",CR
· FOR BCDIndex = MAXBCD - 1 TO 1
····· DEBUG ? BCDIndex
····· BCDDigit(BCDIndex) = 0········ ' clear all digits
· NEXT
· DEBUG ? BCDIndex
· STOP
RETURN

Comments

  • JDJD Posts: 570
    edited 2009-02-14 00:55
    Can you please post the full program?

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Joshua Donelson

    www.parallax.com
  • Mike GreenMike Green Posts: 23,101
    edited 2009-02-14 01:21
    When the FOR statement is executing, it steps from MAXBCD-1 to 1. On the last iteration, the value of BCDIndex is decremented from 1 to 0 and tested against the lower bound (1). The test fails and the FOR / NEXT loop exits. This is pretty standard behavior for most programming languages. The value of the loop variable is "undefined" when the loop exits. Usually it's just outside the loop range. If you run the loop the other way (from 1 to MAXBCD-1) it should exit with BCDIndex equal to MAXBCD (for the same reason).
  • vaclav_salvaclav_sal Posts: 451
    edited 2009-02-14 02:00
    I am planning to post the whole code when I am finished.
    Right now it works but needs some refinement.

    I think posting the whole program for such simple question is unnecessary.

    Actually I was after the BCDIndex value to be set to 0 and though that I could save one line of code doing the loop "backwards"! I am pretty cheap!!
    I like your explanation – makes perfect sense.
    The moral of the story – check the loop counter to make sure it is what you expect!
    Thanks guys.

    !


Sign In or Register to comment.