简体   繁体   中英

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:

- 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM