How to make a Brainfuck: Part 2, implementing the data instructions in C 12-01-2017, 05:31 AM
#1
How to make a Brainfuck: Implementing the data instructions
In this tutorial, we'll be implementing the following operations:
- +
- -
- >
- <
You should have a basic knowledge of C syntax, and of how arrays and pointers work.
How is this going to work?
We need two arrays, one to act as a stack, and another for the cells. Both arrays will be 256 items long, I may go over dynamic data allocation later, but not now.
Lets begin:
Open your favorite text editor, and write a blank main function, along with a 256-item long char array named tape (remember that arrays index from 0), and a pointer to the it, named cell:
Code:
char tape[255];
char *cell = tape;
int main(int argc, char *argv[])
{
}
Then use bzero to fill tape with zeros:
Code:
int main(int argc, char *argv[])
{
bzero(tape, 255);
}
Now, lets see how the operations look in C code:
Code:
+ → ++*cell
- → --*cell
> → ++cell
< → --cell
Next, make a function called interpret, which takes a char array/pointer named instructionList as it's only argument, and returns int.
Code:
int interpret(char *instructionList)
{
}
Not only that, but when you write arrayname[index], this is converted to *(arrayname + index) during compilation... So... arrayname[index] will give the same index[arrayname], which converts to *(index + arrayname).
We need an int x to keep track of where we are, set it to 0. We also need a char named instruction.
Spoiler:
Ok, now let's get to the real code!
Lets make a for loop, which initializes instruction as instructionList[x], checks if instruction is not equal to zero, and increments x at the end.
In the for loop, lets set instruction to instructionList[x], and lets add a switch statement. This switch statement shall execute the code for the instruction that's in instruction, and break.
If you don't know about switch statements, you can read up on them here: https://www.tutorialspoint.com/cprogramm...t_in_c.htm
When you're done with that, you can check your code against this:
Spoiler: code
Conclusion
There we go, you have your data instructions!
Next, we'll implement I/O, '[' and ']', and file reading. In the third tutorial, we'll add error checking, arguments, and extensions.
After that, we'll dive into assembly. You don't have to stay along for that, as it's for more advanced crowds.
At some point, I'd like to make a compiler tutorial, where we convert Brainfuck to NASM, and add some optimizations.
Along with this series, I'm gonna be starting to work on a series on making a cryptocurrency, you should check that out too when it comes out!
Don't forget to post below! Ask questions, comment on this, and discuss anything as long as it's related.
(This post was last modified: 12-01-2017, 07:56 AM by Blink.)