Post Tue Sep 16, 2014 8:57 pm

Conditional operator?

Whenever I'm programming anything in ZX BASIC that involves non-trivial calculations, I really miss the conditional operator from C. So much that I finally decided to post a request here...

Since ZX BASIC already incorporates many useful operators from C like << (binary shift) and & (binary and), could you please consider incorporating C conditional operator also? What I mean is allowing code like this:

  Code:
IF (a < 30) THEN
    LET a = a + 2
ELSE
    LET a = a + 1
END IF


To be written like this:

  Code:
LET a = a + (a < 30 ? 2 : 1)


Those unfamiliar with C programming may not recognize it at first, but after you get used to it, the latter version is a lot easier to read. It's also easier for a compiler to optimize a single expression using conditional operators, instead of multiple IFs. Also this kind of feature would not introduce any problems or ambiguity in the parser.

For more complex expressions it makes a huge difference. Here's another example:

  Code:
IF (row > 0) THEN
    LET pos = pos | (move & UP)
ELSE
    LET pos = pos | TOP
END IF
IF (row < 21) THEN
    LET pos = pos | (move & DOWN)
ELSE
    LET pos = pos | BOTTOM
END IF
IF (col > 0) THEN
    LET pos = pos | (move & LEFT)
ELSE
    LET pos = pos | LEFTMOST
END IF
IF (col < 31) THEN
    LET pos = pos | (move & RIGHT)
ELSE
    LET pos = pos | RIGHTMOST
END IF


Using conditional operators, all this code above would be simplified to this:

  Code:
LET pos = pos | (row > 0 ? move & UP : TOP) |
                (row < 21 ? move & DOWN : BOTTOM) |
                (col > 0 ? move & LEFT : LEFTMOST) |
                (col < 31 ? move & RIGHT : RIGHTMOST)


Makes sense?