Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active January 24, 2016 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Garciat/e7fcf0f371673cda57d0 to your computer and use it in GitHub Desktop.
Save Garciat/e7fcf0f371673cda57d0 to your computer and use it in GitHub Desktop.
PUSH 8
PUSH 2
ADD
PUSH 32
ADD
PRINT
PUSH 42
PRINT
PUSH 100
PRINT
PUSH 21
DUP
ADD
PRINT
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
int pila[100];
int tope = 0;
string instr;
while (cin >> instr) {
if (instr == "PUSH") {
int val;
cin >> val;
pila[tope] = val;
tope += 1;
} else if (instr == "ADD") {
if (tope < 2) {
abort();
}
int a = pila[tope - 1];
int b = pila[tope - 2];
tope -= 2;
pila[tope] = a + b;
tope += 1;
} else if (instr == "PRINT") {
if (tope < 1) {
abort();
}
int val = pila[tope - 1];
tope -= 1;
cout << val << endl;
} else if (instr == "DUP") {
if (tope < 1) {
abort();
}
int val = pila[tope - 1];
pila[tope] = val;
tope += 1;
} else {
cerr << "mala instruccion" << endl;
abort();
}
}
}
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main() {
int pila[100];
int tope = 0;
string instr;
cout << "#include <stdio.h>" << endl;
cout << "int main() {" << endl;
cout << "int pila[100] = { 0 }, tope = 0, x1, x2;" << endl;
while (cin >> instr) {
if (instr == "PUSH") {
int val;
cin >> val;
cout << "pila[tope] = " << val << ";" << endl;
cout << "tope += 1;" << endl;
} else if (instr == "ADD") {
cout << "x1 = pila[tope - 1];" << endl;
cout << "x2 = pila[tope - 2];" << endl;
cout << "tope -= 2;" << endl;
cout << "pila[tope] = x1 + x2;" << endl;
cout << "tope += 1;" << endl;
} else if (instr == "PRINT") {
cout << "x1 = pila[tope - 1];" << endl;
cout << "tope -= 1;" << endl;
cout << "printf(\"%d\\n\", x1);" << endl;
} else if (instr == "DUP") {
cout << "x1 = pila[tope - 1];" << endl;
cout << "pila[tope] = x1;" << endl;
cout << "tope += 1;" << endl;
} else {
cerr << "mala instruccion" << endl;
abort();
}
}
cout << "}" << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment