开发者

C Compare operator precedence

Hi there i have a method called

int compare(char op1, char op2)

the method will return 1, -1 or 0 depending on the result of the comparison. (1 if op1 < op2).

I need to compare the following operations开发者_如何学C:

- subtraction
* multiplication
/ division
^ exponentiation
% remainder

I have considered using an enum such as:

enum ops{
    '+'=1, '-'=1, '*'=2, '/'=2, '^', '%'
}var;

but this doesn't compile. Can anyone lend a hand?


You can't use characters as keys for the enum, you should do something like:

enum ops {
    OP_PLUS       = 1,
    OP_MINUS      = 1,
    OP_MULT       = 2,
    OP_DIV        = 2,
    OP_POWER,
    OP_MOD
} var;


enums have to be identifier names, not characters. I suggest naming them PLUS, MINUS, etc. (Also, why would % have higher precedence than ^? The de facto standard is to give % the same precedence as * and /.)


#include <stdio.h>

struct precedence
{
  char op;
  int prec;
} precendence[] =
{ { '+', 1 },
  { '-', 1 },
  { '*', 2 },
  { '/', 2 },
  { '^', 3 },
  { '%', 4 },
  { 0, 0 }};

int compare(char *a, char *b)
{
  int prec_a = 0, prec_b = 0, i;

  for(i=0; precendence[i].op && (!prec_a || !prec_b); i++)
  {
    if (a == precendence[i].op)
      prec_a = precendence[i].prec;
    if (b == precendence[i].op)
      prec_b = precendence[i].prec;
  }

  if (!prec_a || !prec_b)
  {
    fprintf(stderr,"Could not find operator %c and/or %c\n",a,b);
    return(-2);
  }
  if (prec_a < prec_b)
    return -1;
  if (prec_a == prec_b)
    return 0;
  return 1;
}


main()
{
  char a,b;

  a='+'; b='-'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
  a='+'; b='*'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
  a='+'; b='^'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
  a='+'; b='%'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
  a='*'; b='+'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
  a='^'; b='+'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
  a='%'; b='+'; printf("Prec %c %c is %d\n", a,b,compare(a,b));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜