c - 使用一组运算符在 C 中定义宏
问题描述
我在编程方面相对较新,我试图通过以下方式定义一个名为 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 代码,您无法将 achar
与无论如何都没有意义的字符数组进行比较。
你要这个:
#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;
}
推荐阅读
- mysql - 多对多关系 Laravel 与不同的值、产品属性
- reactjs - 检查是否使用 Jest 在 axios 拦截器中调用调度操作
- c# - !(x is null) 和 x is object 之间有区别吗
- ios - 为什么 UISearchController 会改变导航栏的颜色?
- apache-spark - 如何让 AWS 上的本地 Spark 写入 S3
- azure - Azure 文件共享访问签名在结束日期之前过期
- java - Android Studios:我无法访问方法 onLocationResult(LocationResult locationResult),当我尝试自己覆盖它时它给了我一个错误
- typescript - 如何在 TypeScript 中将类型化的键值数组转换为 ES6 映射?
- reactjs - Firebase onAuthStateChanged 与 React 上下文未更新应用程序
- batch-file - 如何修复“命令的语法不正确”。错误