Execute Brain****/C: Difference between revisions

No edit summary
Line 225:
#include <stdlib.h>
#include <string.h>
 
char *nested_loop (char *s, char *tape, int d) {
char *p = ++s;
while(*p != ']') {
int c = *p;
switch(c) {
case '+': tape[d]++; break;
case '-': tape[d]--; break;
case '>': d++; break;
case '<': d--; break;
case '.': putchar(tape[d]); break;
case ',': tape[d] = getchar(); break;
case '[': p = nested_loop(p, tape, d); break;
default: break;
}
p++;
if(*p == ']' && tape[d] != 0) p = s;
}
return p;
}
 
void bf_run(char *s) {
int len = strlen(s), d = 0;
char *tape = calloc(len, sizeof(char));
int brack = 0;
for (; d >= 0 && *s; s++) {
if (*s == '[') { //if there is a loop
char *p = ++s;
while(*p != ']') { //take care of the loop part
int c = *p;
switch(c) {
Line 243 ⟶ 266:
case '.': putchar(tape[d]); break;
case ',': tape[d] = getchar(); break;
case '[': p = nested_loop(p, tape, d); break;
default: break;
}
 
p++;
if(*p == ']' && tape[d] != 0) p = s; //the loop stops when the cell has value equal to 0
}
s = p + 1;
}
Anonymous user