c - C 中的宏复合表达式中的“预期表达式”错误
问题描述
我试图构建一个已定义的宏函数来将元素搜索到选项卡中,但编译器返回错误:
test2.c:27:11: error: expected expression
ret = SEARCH(tab, targ);
^
我不明白这个错误,因为我的赋值语句是一个表达式。
这受到 GNU 编译器文档中给出的示例代码的启发:https ://gcc.gnu.org/onlinedocs/gcc/Local-Labels.html#Local-Labels
#include <stdio.h>
#include <stdlib.h>
#define NUM_EL 10
#define TAB_SIZE = NUM_EL -1
#define SEARCH(array, target) \
({ \
__label__ found; \
typeof (target) _SEARCH_target = (target); \
typeof (*(array)) *_SEARCH_array = (array); \
int i; \
int value; \
for(i = 0; i <= TAB_SIZE; i++); \
if (_SEARCH_array[i] == _SEARCH_target) \
{ value = i; goto found;} \
value= -1; \
found: \
value; \
})
int main() {
int tab[NUM_EL] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int ret = 0, targ = 5;
printf("Exemple test!\n");
ret = SEARCH(tab, targ);
}
编辑已解决:这是更正并正常工作的代码
#include <stdio.h>
#include <stdlib.h>
#define NUM_EL 10
#define TAB_SIZE NUM_EL - 1
#define SEARCH(array, target) \
({ \
__label__ found; \
typeof (target) _SEARCH_target = (target); \
typeof (*(array)) *_SEARCH_array = (array); \
int i; \
int value; \
for(i = 0; i <= TAB_SIZE; i++) \
if (_SEARCH_array[i] == _SEARCH_target) \
{ value = i; goto found;} \
value= -1; \
found: \
value; \
})
int main() {
int tab[NUM_EL] = {10, 52, 98, 45, 12, 31, 15, 1, -74, -10};
int targ = 52;
printf("Exemple test!\n");
int res = SEARCH(tab, targ);
res != -1 ? \
printf("tab[%d] --> %d\n", res, targ) : \
printf("%d Not found!\n",targ);
}
解决方案
TL:DR:在您完全理解基本的 C 语法之前,不要尝试处理复杂的宏。
问题是你的宏
#define TAB_SIZE = NUM_EL - 1
这使得TAB_SIZE
扩展为令牌序列= NUM_EL -1
。因此,在你的SEARCH
宏中,你最终得到
for (i = 0; i <= = NUM_EL - 1; i++);
另请注意,;
onfor
使这是一个空循环(什么都不做),因此您的代码不会执行您期望的操作。
推荐阅读
- python - Django:我的函数返回一个对象而不是返回值
- sql - 在 Altibase DBMS 中测量执行时间
- amazon-web-services - AWS Lambda ListVersionsByFunction 返回的版本是否已排序?
- r - 按 r 中的列值标记 nmds 图
- rabbitmq - 发现在 RabbitMQ 中等待消息的队列
- node.js - 从 Javascript/Node 获取 Skype 状态
- unit-testing - 使用 jest-express,如何对给定请求调用中间件进行单元测试?
- python - Tensorboard 摘要卡在 0
- c# - 使用可视化 C# 写入另一个程序的另存为对话框
- javascript - 如何检查用户是否在控制台中输入了某些内容?Javascript