Skip to main content
9 of 16
updated un-golfed printing function and comments
luser droog
  • 4.9k
  • 2
  • 36
  • 61

C 924 882 622 591 chars

With obvious newlines removed (retained for readability).

#define A sbrk(8);signal(11,S);
#define U *t++
#define P t>s?*--t:0
#define W(x)write(1,&x,1);
#define B(x,y)break;case 48+x:b=48+x;W(b)w=P;y;U=w;
*s,*t,w,a,c,d;char b;S(x){A}
p(x){if(x<0){W(*"-")x=-x;}if(x>9)p(x/10);b=48+x%10;W(b)}
main(){t=s=A
U=0;while(read(0,&b,1))switch(b){
B(0,w+=a*pow(10,ceil(log10(w))))
B(1,++w)
B(2,--w)
B(3,w*=P)
B(4,w=P/w)
B(5,w+=P)
B(6,w=P-w)
B(7,w=pow(P,w))
B(8,w=P%w)
B(9,*t=w;w=*s;memmove(s,s+1,4*(t-s)))
B(17,memmove(s+1,s,4*(t++-s));*s=w;w=P)
B(18,U=w)
B(19,a=P;U=a;U=w;U=a)
B(20,a=P;U=w;w=a)
B(21,a=P;c=P;d=P;U=a;U=w;U=c;w=d)
B(22,w=P)}
for(W(*"[")t>s;)p(P),W(*" ")
W(*"]")
}

This implements the "underflow pushes zero" interpretation from Jan Dvorak's comment.

Ungolfed:

#include<math.h>
#include<signal.h>
void S(int x){signal(SIGSEGV,S);sbrk(8*8*8);}
int*s,*t,*i,w,a,c,d;    //stack top index working accumulator count data
u(x){*t++=x;}           //push()
o(){return t>s?*--t:0;} //pop()
p(x){                   //print()
    if(x<0){    //negative?
        W(*"-") //output '-'
        x=-x;   //negate
    }
    if(x>9)     //more than one digit?
        p(x/10); //recurse after integer-divide
    b=48+x%10;   //isolate and convert single digit to ascii
    W(b)         //output ascii digit
}
main(){
    char b[1];
    signal(SIGSEGV,S);  //auto-allocate memory for stack
    t=s=sbrk(8*8*8);  //get start of memory and allocate
    while(read(0,b,1)){
        write(1,b,1); //for debugging: echo the command being executed
        switch(*b){
            case '0': w=o(); a=o(); for(c=ceil(log10(w));c>0;c--) a*=10; u(a+w); break;
            case '1': u(o()+1); break;
            case '2': u(o()-1); break;
            case '3': w=o(); u(o()*w); break;
            case '4': w=o(); u(o()/w); break;
            case '5': u(o()+o()); break;
            case '6': w=o(); u(o()-w); break;
            case '7': c=o();a=1; for(w=o();c>0;c--) a*=w; u(a); break;
            case '8': w=o(); u(o()%w); break;
            case '9': w=*s; memmove(s,s+1,4*(t-s-1)); t[-1]=w; break;
            case 'A': w=t[-1]; memmove(s+1,s,4*(t-s-1)); *s=w; break;
            case 'B': w=o(); u(w); u(w); break;
            case 'C': w=o(); a=o(); u(a); u(w); u(a); u(w); break;
            case 'D': w=o(); a=o(); u(w); u(a); break;
            case 'E': w=o(); a=o(); c=o(); d=o(); u(a); u(w); u(d); u(c); break;
            case 'F': o(); break;
        }
    }
    write(1,"\n[",2);   //dump the stack
    i=t;
    do {
        p(*--i);
    } while(i>s && write(1,",",1));
    write(1,"]\n",2);
}
luser droog
  • 4.9k
  • 2
  • 36
  • 61