Created
November 6, 2023 12:03
-
-
Save adamsir/94aa847cc710093c48da1fb822f4e8bf to your computer and use it in GitHub Desktop.
Brainfuck interpreter in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#define TAPE_SIZE 30000 | |
// Declare an array to act as the tape for Brainfuck. Initialize all to zero. | |
unsigned char s[TAPE_SIZE] = {0}; | |
// This will be the data pointer used in Brainfuck | |
unsigned char* ptr = s; | |
// Forward declaration of the main function to make it recursive | |
int main(int argc, char *argv[]); | |
int main(int argc, char *argv[]) { | |
char* v; | |
// Ensure that a Brainfuck program is provided as an argument | |
if (argc != 2) { | |
fprintf(stderr, "Usage: %s 'brainfuck_code'\n", argv[0]); | |
return 1; | |
} | |
v = argv[1]; | |
while (*v) { | |
switch (*v) { | |
case '>': | |
ptr++; | |
// Boundary check to prevent going beyond the tape | |
if (ptr >= s + TAPE_SIZE) { | |
fprintf(stderr, "Error: Pointer out of bounds\n"); | |
return 1; | |
} | |
break; | |
case '<': | |
// Boundary check to prevent going before the tape | |
if (ptr <= s) { | |
fprintf(stderr, "Error: Pointer out of bounds\n"); | |
return 1; | |
} | |
ptr--; | |
break; | |
case '+': | |
(*ptr)++; | |
break; | |
case '-': | |
(*ptr)--; | |
break; | |
case '.': | |
putchar(*ptr); | |
break; | |
case ',': | |
*ptr = (unsigned char)getchar(); | |
break; | |
case '[': | |
if (!*ptr) { | |
int loop = 1; | |
while (loop > 0) { | |
v++; | |
if (*v == '[') loop++; | |
if (*v == ']') loop--; | |
} | |
} | |
break; | |
case ']': | |
if (*ptr) { | |
int loop = 1; | |
while (loop > 0) { | |
v--; | |
if (*v == '[') loop--; | |
if (*v == ']') loop++; | |
} | |
} | |
break; | |
} | |
v++; | |
} | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment