title: Equation (expression) parser with precedence?
body: <p>I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &amp;, *, /, etc) operators, unary (!) operators, and parenthesis.</p>
  <p>Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis.</p>
  <p>So right now &quot;1+11*5&quot; returns 60, not 56 as one might expect.</p>
  <p>While this is suitable for the current project, I want to have a general purpose routine I can use for later projects.</p>
  <p><strong>Edited for clarity:</strong></p>
  <p>What is a good algorithm for parsing equations with precedence?</p>
  <p>I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code.</p>
  <p><strong>Grammar:</strong></p>
  <p>I don't understand the grammar question - I've written this by hand.  It's simple enough that I don't see the need for YACC or Bison.  I merely need to calculate strings with equations such as &quot;2+3 * (42/13)&quot;.</p>
  <p><strong>Language:</strong></p>
  <p>I'm doing this in C, but I'm interested in an algorithm, not a language specific solution.  C is low level enough that it'll be easy to convert to another language should the need arise.</p>
  <p><strong>Code Example</strong></p>
  <p>I posted the <a href="http://web.archive.org/web/20171012060859/http://www.ubasics.com/simple_c_equation_parser" rel="noreferrer">test code for the simple expression parser</a> I was talking about above.  The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project.  It's in the original verbose form, and should be readily understandable.  If I do anything further with it in terms of operator precedence, I'll probably choose <a href="https://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/783132#783132">the macro hack</a> because it matches the rest of the program in simplicity.  If I ever use this in a real project, though, I'll be going for a more compact/speedy parser.</p>
  <p><strong>Related question</strong></p>
  <blockquote>
  <p><a href="https://stackoverflow.com/questions/114586/smart-design-of-a-math-parser">Smart design of a math parser?</a></p>
  </blockquote>
  <p>-Adam</p>