c - How do I make this compact, efficient and readable? -


so have bit of code parses chunk of mathematical expression between operators. instance, mathematical expression

x^2+5.09*x+(123.1+x) 

looks

[expr_0][op_1][expr_1][op_2][expr_2][op_3][expr_3] 

where

expr_0 = 'x' op_1 = '^' expr_1 = '2' op_2 = '+' expr_2 = '5.09' op_3 = '*' expr_3 = 'x' op_4 = '+' expr_4 = '123.1+x' 

in algorithm there comes point current character in math function string expected beginning of expression (one of expr_0, expr_1, expr_2 or expr_3 above) need put expression in string , advance pointer current character 1 beyond expression. expression either 'x', number (e.g. '5.09') or expression in parenthesis.

my function described in above paragraph looks

node * getnextexpression ( char ** begptr ) {     // begptr: pointer character @ beginning of expression      node * result;      if (**begptr == 'x') // next expression variable 'x'     {         result = malloc(sizeof(node));         result->fx = "x"; result->gx = null; result->op = null; result->hx = null;     }     else if ((**begptr >= '0' && **begptr  <= '9') || **begptr== '.') // next expression number     {         int foundperiod = 0;         char * cpy = *begptr;                 {             if (**begptr == '.')             {                 if (foundperiod == 0) foundperiod = 1;                 else break;             }             ++*begptr;         } while ((**begptr >= '0' && **begptr  <= '9') || **begptr == '.');         long n = *begptr - cpy;         char * numstr = malloc(sizeof(char) * (n + 1));         numstr[n] = '\0';         (long k = 0; k < n; ++k) numstr[k] = *cpy++;         result->fx = numstr; result->gx = null; result->op = null; result->hx = null;     }     else if (**begptr == '(') // next expression enclosed in parantheses     {         // .... haven't got down yet     }     else     {         result = null;     }     return result; } 

which complete mess , possibly wrong. there more compact procedure getting number string numstr, meanwhile advancing pointer *begptr?

for reference, node is

typedef struct node {     char * fx; // function     struct node * gx; // left-hand side     char * op; // operator     struct node * hx; // right-hand side } node; 


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -