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

Content added Content deleted
No edit summary
Line 225: Line 225:
#include <stdlib.h>
#include <stdlib.h>
#include <string.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) {
void bf_run(char *s) {
int len = strlen(s), d = 0;
int len = strlen(s), d = 0;
char *tape = calloc(len, sizeof(char));
char *tape = calloc(len, sizeof(char));
int brack = 0;
for (; d >= 0 && *s; s++) {
for (; d >= 0 && *s; s++) {
if (*s == '[') { //if there is a loop
if (*s == '[') {
char *p = ++s;
char *p = ++s;
while(*p != ']') { //take care of the loop part
while(*p != ']') {
int c = *p;
int c = *p;
switch(c) {
switch(c) {
Line 243: Line 266:
case '.': putchar(tape[d]); break;
case '.': putchar(tape[d]); break;
case ',': tape[d] = getchar(); break;
case ',': tape[d] = getchar(); break;
case '[': p = nested_loop(p, tape, d); break;
default: break;
default: break;
}
}

p++;
p++;
if(*p == ']' && tape[d] != 0) p = s; //the loop stops when the cell has value equal to 0
if(*p == ']' && tape[d] != 0) p = s;
}
}
s = p + 1;
s = p + 1;
}
}