Skip to content

Instantly share code, notes, and snippets.

@radiofreejohn
Created March 18, 2011 08:12
Show Gist options
  • Save radiofreejohn/875765 to your computer and use it in GitHub Desktop.
Save radiofreejohn/875765 to your computer and use it in GitHub Desktop.
K&R Exercise 5-10, reverse polish notation evaluator, this is rough
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
float polishStack[100];
float *stackPtr;
float tempx, tempy;
float *start;
stackPtr = polishStack;
start = stackPtr;
// don't really need this here, but i'll go with it
*stackPtr++ = 0.0;
*argv++;
// so funny, * on arg is glob in bash, thanks
// try \* to make it work
while (--argc)
{
// check if first character of current argument
// is punctuation (this includes math ops)
// and that we won't underflow the stack
if (ispunct(**argv) && (stackPtr-2) > start)
{
tempx = *--stackPtr;
tempy = *--stackPtr;
printf("%f %c %f\n", tempy, **argv, tempx);
if (**argv == '+')
{
//pop off stack, push solution to stack
*stackPtr++ = tempx + tempy;
} else if (**argv == '-')
{
*stackPtr++ = tempy - tempx;
} else if (**argv == '/')
{
*stackPtr++ = tempy/tempx;
} else if (**argv == '*')
{
*stackPtr++ = tempx*tempy;
} else {
// no operator, push temp back
*stackPtr++ = tempy;
*stackPtr++ = tempx;
}
*argv++;
}
else if (isdigit(**argv))
{
*stackPtr++ = atof(*argv++);
}
}
if (stackPtr-2 == start)
printf("%f \n", *--stackPtr);
else
printf("Too many inputs\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment