computedGoto pragma

The computedGoto pragma can be used to tell the compiler how to compile a Nim case in a while true statement. Syntactically it has to be used as a statement inside the loop:

  1. type
  2. MyEnum = enum
  3. enumA, enumB, enumC, enumD, enumE
  4. proc vm() =
  5. var instructions: array[0..100, MyEnum]
  6. instructions[2] = enumC
  7. instructions[3] = enumD
  8. instructions[4] = enumA
  9. instructions[5] = enumD
  10. instructions[6] = enumC
  11. instructions[7] = enumA
  12. instructions[8] = enumB
  13. instructions[12] = enumE
  14. var pc = 0
  15. while true:
  16. {.computedGoto.}
  17. let instr = instructions[pc]
  18. case instr
  19. of enumA:
  20. echo "yeah A"
  21. of enumC, enumD:
  22. echo "yeah CD"
  23. of enumB:
  24. echo "yeah B"
  25. of enumE:
  26. break
  27. inc(pc)
  28. vm()

As the example shows computedGoto is mostly useful for interpreters. If the underlying backend (C compiler) does not support the computed goto extension the pragma is simply ignored.