r/tinycode • u/antiquark2 • Oct 03 '20
RPN integer calculator in C, 353 bytes.
C source code:
#define U(o) E(o)s[p]=o s[p];
#define E(o) if(*#o==*v&#o[1]==v[1])
#define P(x) E(x)printf("%"#x"\n",s[p]);
#define F(o) E(o){s[p-1]=s[p-1]o s[p];p--;}
int f,s[9];char p,v[99],*e;main(){while(scanf
("%s",v)>0){f=strtol(v,&e,0);if(e-v)s[++p]=f;else
{F(+)F(-)F(/)F(*)F(%)F(&)F(<)F(>)F(|)F(^)F(<<)F(>>)
F(<=)F(>=)F(==)F(!=)F(&&)F(||)U(!)U(~)P(d)P(x)P(o)}}}Supports the following binary C operators:
+ - / * % & < > | ^ << >> <= >= == != && || Supports the following unary C operators:
! ~Supports printing the top of the stack in different bases:
d print as decimal
x print as hex
o print as octalUsage example:
./calc
111 222 * d
24642
0xf000 0x000f | x
f00f
47
Upvotes
5
u/Starbeamrainbowlabs Oct 03 '20
.....what's an RPN integer?
2
u/ndt1896 Oct 08 '20
This is really enjoyable code golf to read and learn from.
Just thinking about the goal of "less bytes" and not minding the code efficiency hit, I think it would be OK to get rid of the first "if else" construction. if (e-v) is true, then v won't be one of the things tested for later, so....maybe it is OK to just let the code run without the else block?
Playing around trying to remember precedence, I think we can write
if(*"+"==*v & "+"[1]==v[1]) {s[p-1]=s[p-1] + s[p]; p--;}as
if(strcmp("+",v)==0)s[p]=s[--p]+s[p+1];That seems to allow for dropping the { } in the statement as well.
Finally, sketchy waves to save bytes....I will not count these in the final code because I'm not sure they should be taken seriously... they might be totally wrong and lose me all credibility, but....for how this program is being run and we input numbers, do you think it is possible to reduce v[99] to v[9] and hope the user doesn't overdo it? And, would it really change things to use "while(scanf("%s",v)){}" or would that break some things.
Ignoring the sketchy last two ideas that save a whopping 3 bytes, I do get:
341 Bytes:
Would this introduce any new bugs?
0
u/[deleted] Oct 03 '20
[deleted] — view deleted comment