Skip to content

Instantly share code, notes, and snippets.

@maksimKorzh
Last active October 11, 2021 12:40
Show Gist options
  • Save maksimKorzh/8bb25010330c14519a5f76d38f343342 to your computer and use it in GitHub Desktop.
Save maksimKorzh/8bb25010330c14519a5f76d38f343342 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define TAPE_SIZE 30000
#define SOURCE_SIZE 30000
char tape[TAPE_SIZE];
// cell is like tape[0] and if we say cell = cell + 1 then it's like tape[1]
char *cell = tape;
char source[SOURCE_SIZE] = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
char *ip = source; // instruction pointer
int loop;
int main()
{
while(*ip)
while(*ip)
{
switch(*ip)
{
case '>': ++cell; break;
case '<': --cell; break;
case '+': ++*cell; break;
case '-': --*cell; break;
case '.': putchar(*cell); break;
case ',': *cell = getchar(); break;
case '[':
if(!*cell) //*cell == 0 /* if cell at data pointer is zero */
{
loop = 1; /* loop variable holds a number of '[]' */
while(loop) // loop != 0 /* do until find matching ']' */
{
ip++; //sorry guys, *ip++ works but basically wrong, so removing '*' /* increment instruction pointer */
if(*ip == '[') loop++; // loop = loop + 1 /* inc loop on '[' instruction */
if(*ip == ']') loop--; /* dec loop on ']' instruction */
}
}
break;
case ']':
loop = 1; /* loop variable holds a number of '[]' */
while(loop) // loop != 0 /* do until find matching '[' */
{
ip--; // same here /* decrement instruction pointer */
if(*ip == '[') loop--; /* dec loop on '[' instruction */
if(*ip == ']') loop++; /* inc loop on ']' instruction */
}
ip--; // and here /* decrement instruction pointer */
break;
}
//printf("cell address: '%d'\n", cell);
//putchar(*ip);
ip++; // ip = ip + 1;
}
//for(int i = 0; i < 10; i++) { printf("%d, ", tape[i]); }
printf("\n");
return 0;
}
@opain-replika
Copy link

Thank you, this helped me implement my own bf interpreter. I had really hard time implementing loops.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment