PageRenderTime 72ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/brainfuck/bf.c

http://stuffpack.googlecode.com/
C | 78 lines | 72 code | 1 blank | 5 comment | 23 complexity | 979492ff6603b9a7a8aa36efc25ad1e2 MD5 | raw file
  1. /*
  2. A naive and quick implementation of brainfuck
  3. Eitan Adler
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #define PROGSIZE 4096
  8. int main(void) {
  9. int matchcount;
  10. //Start off with a small stack and grow
  11. unsigned int stacksize = 25;
  12. int *stack = calloc(stacksize,sizeof(int));
  13. char program[PROGSIZE] = { 0 };
  14. fgets(program,PROGSIZE, stdin);
  15. unsigned int sp = 0;
  16. unsigned int ip = 0;
  17. while (program[ip] != 0) {
  18. switch ((int)program[ip]) {
  19. case '>':
  20. ++sp;
  21. break;
  22. case '<':
  23. --sp;
  24. break;
  25. case '+':
  26. ++(stack[sp]);
  27. break;
  28. case '-':
  29. --(stack[sp]);
  30. break;
  31. case '.':
  32. printf("%c",stack[sp]);
  33. break;
  34. case ',':
  35. scanf("%c",stack[sp]);
  36. break;
  37. case '[':
  38. matchcount = 1;
  39. if (stack[sp] == 0){
  40. while (matchcount != 0) {
  41. ++ip;
  42. if (program[ip] == '['){
  43. matchcount++;
  44. }
  45. else if (program[ip] == ']') {
  46. matchcount--;
  47. }
  48. }
  49. }
  50. break;
  51. case ']':
  52. matchcount = 1;
  53. if (stack[sp] != 0){
  54. while (matchcount != 0) {
  55. --ip;
  56. if (program[ip] == ']'){
  57. matchcount++;
  58. }
  59. else if (program[ip] == '[') {
  60. matchcount--;
  61. }
  62. }
  63. }
  64. break;
  65. }
  66. if (sp > stacksize) {
  67. const unsigned int oldsize = stacksize;
  68. stacksize *= 1.5;
  69. realloc(stack, stacksize);
  70. for (unsigned int i = oldsize; i < stacksize; ++i) {
  71. stack[i] = 0;
  72. }
  73. }
  74. ++ip;
  75. }
  76. return 0;
  77. }