POV-Ray : Newsgroups : povray.off-topic : My first C++ program : Re: My first C++ program Server Time
30 Sep 2024 13:19:27 EDT (-0400)
  Re: My first C++ program  
From: scott
Date: 19 Sep 2008 08:23:31
Message: <48d399c3@news.povray.org>
> I also find myself constantly cursing that I have to write an entire 5 
> lines of (nearly identical) code for every arithmetic operation I want to 
> implement and there's no way to abstract this. (I don't have copy & paste 
> available!)

What you could do, is have a function like DoOperation(stack,op), and use 
"op" as a token for the operation.

So you would call it like:

     if (cmd == "+") {DoOP(stack,0); continue;}
     if (cmd == "-") {DoOP(stack,1); continue;}
     if (cmd == "/") {DoOP(stack,2); continue;}
     if (cmd == "*") {DoOP(stack,3); continue;}

Or you could even use some fancy look-up table to convert from the character 
code to op number, or just use the ASCII code of the operator as the op 
number... you get the idea.

Then, DoOperation() would look like:

   if (!StackCheck(stack, 2)) return;

   int x = stack.back(); stack.pop_back();
   int y = stack.back(); stack.pop_back();
   int answer;
   if(op==0) answer=x+y;
   if(op==1) answer=x-y;
   if(op==2) answer=x/y;
   if(op==3) answer=x*y;
   stack.push_back(answer);

I'm sure there's a better way of doing it, but I think that's less work than 
your first version.

PS good work on the first C++ program, it's way cooler than any of my first 
programs.


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.