Fixed bug for nested loops.
This commit is contained in:
2
Makefile
2
Makefile
@@ -7,7 +7,7 @@ HFILES=$(shell find . -name '*.h')
|
|||||||
STYLE=astyle --style=1tbs
|
STYLE=astyle --style=1tbs
|
||||||
RUN=valgrind --leak-check=full
|
RUN=valgrind --leak-check=full
|
||||||
DEBUG=gdb --args
|
DEBUG=gdb --args
|
||||||
ARGS="examples/hello.bf"
|
ARGS="examples/rot13.bf"
|
||||||
|
|
||||||
all: build run
|
all: build run
|
||||||
|
|
||||||
|
|||||||
24
bfckr.c
24
bfckr.c
@@ -39,6 +39,8 @@ void die(const char *message)
|
|||||||
// Parses and executes a brainfuck expression
|
// Parses and executes a brainfuck expression
|
||||||
void bfuck_parser(char *input)
|
void bfuck_parser(char *input)
|
||||||
{
|
{
|
||||||
|
int loop = 0;
|
||||||
|
|
||||||
for(size_t i = 0; input[i] != 0; i++) { // where i is the instruction pointer
|
for(size_t i = 0; input[i] != 0; i++) { // where i is the instruction pointer
|
||||||
switch(input[i]) {
|
switch(input[i]) {
|
||||||
case '>':
|
case '>':
|
||||||
@@ -68,8 +70,16 @@ void bfuck_parser(char *input)
|
|||||||
case '[':
|
case '[':
|
||||||
if(*p == 0) { // if the byte at the data pointer is zero
|
if(*p == 0) { // if the byte at the data pointer is zero
|
||||||
// jump forward to the command after the next ]
|
// jump forward to the command after the next ]
|
||||||
while(input[i] != ']') {
|
loop = 1;
|
||||||
|
// jump back to the command after the matching [
|
||||||
|
while(loop > 0) {
|
||||||
i++;
|
i++;
|
||||||
|
if(input[i] == '[') {
|
||||||
|
loop++;
|
||||||
|
}
|
||||||
|
if(input[i] == ']') {
|
||||||
|
loop--;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
continue; // increment instruction pointer
|
continue; // increment instruction pointer
|
||||||
@@ -78,10 +88,18 @@ void bfuck_parser(char *input)
|
|||||||
|
|
||||||
case ']':
|
case ']':
|
||||||
if(*p != 0) { // if the byte at the data pointer is nonzero
|
if(*p != 0) { // if the byte at the data pointer is nonzero
|
||||||
// jump back to the command after the previous [
|
loop = 1;
|
||||||
while(input[i] != '[') {
|
// jump back to the command after the matching [
|
||||||
|
while(loop > 0) {
|
||||||
i--;
|
i--;
|
||||||
|
if(input[i] == '[') {
|
||||||
|
loop--;
|
||||||
|
}
|
||||||
|
if(input[i] == ']') {
|
||||||
|
loop++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
continue; // increment instruction pointer
|
continue; // increment instruction pointer
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user