2

How would one go about branching in GNU dc? OpenBSD's implementation has conditionals with an else-branch, but GNU's does not... so you can conditionally execute one macro, but when it completes it drops you back in the same place in the code.

It seems like it could maybe be accomplished by leaving a sentinel value on the stack, but that's error-prone (especially so since dc can't do string comparison, so we're left with sentinels that are just numbers).

Maybe something to do with q/Q ?

Is this even possible?

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
SAyotte
  • 387
  • 3
  • 9

1 Answers1

3

I think I figured it out!

By using q/Q within a sub-macro, I return to one level above the calling macro, thus skipping any further code within the caller. If I called the sub-macro conditionally, this has the effect of making the rest of the calling-macro the "else" branch.

[[Input is an odd number.]P]sa
[[Input is an even number.]Pq]sb
[2%0=blax]sc
1lcx
Input is an odd number.
2lcx
Input is an even number.
SAyotte
  • 387
  • 3
  • 9
  • 1
    There are a few ways to approach this, but this is one of them, and one of the more readable methods at that. [Here](https://codegolf.stackexchange.com/questions/77698/tips-for-golfing-in-dc/84327#84327) is an answer with some other methods. Personally, when I work with quitting macros, I opt for `2Q` rather than `q`, just to be safe. `q` has the ability to exit the program—it shouldn't ever do that in this case, but you never know! :) – Joe Nov 02 '17 at 08:22