使用一组运算符在 C 中定义宏

Defining a Macro in C with a set of operators

我在编程方面相对较新,我试图通过以下方式定义一个名为 OPERATORS 的宏:

#define OPERATORS {'+', '-','*', '/', '%', '^'}

这个,目的是制作以下程序:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define OPERATORS {'+', '-','*', '/', '%', '^'}

int isOperator (char c) {
    if(c!=OPERATORS)
        return 0;
    return 1;
}

int main(){
    printf("%d", isOperator('+'));
    printf("%d", isOperator('j'));
    return 0;
}

判断字符c是不是运算符。 但是我在编译器方面遇到了问题,我确定这与宏的声明有关。所以我的问题是:

如何使用一组运算符定义宏以及如何使用它?? '因为我几乎可以肯定,要将变量与宏进行比较,应该以不同的方式进行 抱歉我的无知,非常感谢!

宏只做文本替换,所以你的代码实际上等同于:

int isOperator (char c) {
    if (c != {'+', '-','*', '/', '%', '^'})
        return 0;

    return 1;
}

这是无效的 C 代码,您不能将 char 与无论如何都没有意义的字符数组进行比较。

你想要这个:

#include <stdio.h>
#include <stdlib.h>

int isOperator(char c) {
  static char operators[] = { '+', '-','*', '/', '%', '^' };
  for (int i = 0; i < sizeof operators; i++)
    if (c == operators[i])
      return 1;

  return 0;
}

int main() {
  printf("%d\n", isOperator('+'));
  printf("%d\n", isOperator('j'));
  return 0;
}

或更短:

...
#include <string.h>
...
int isOperator(char c) {
  char operators[] = "+-*/%^";
  return strchr(operators, c) != NULL;
}

你也可以使用查找table

#include <stdint.h>

const int type[256] = {['%'] = 1, ['+'] = 1, ['-'] = 1, ['/'] = 1, ['*'] = 1, ['^'] = 1, ['!'] = 1, 
                       ['0'] = 2, ['1'] = 2, ['2'] = 2, ['3'] = 2, ['4'] = 2, ['5'] = 2, ['6'] = 2, ['7'] = 2, ['8'] = 2, ['9'] = 2,
};

int myisoperator(int c)
{
    return type[c] == 1;
}

int myisdigit(int c)
{
    return type[c] == 2;
}