我想根据传递给宏的值来调用特定函数。但它给了我编译错误
#include <stdio.h>
#define calling(m, j) execcall ## m(j);
void execcall0 (int x) {
printf("called 0 with arg %d\n", x);
}
void execcall1 (int x) {
printf("called 1 with arg %d\n", x);
}
void execcall2 (int x) {
printf("called 2 with arg %d\n", x);
}
int main () {
int i = 0;
for (i = 0; i < 3; i++) {
calling(i, 1);
}
}
编译错误:
In function `main':
new.c:(.text+0x7a): undefined reference to `execcalli'
collect2: ld returned 1 exit status
甚至可能无论我在尝试什么?
答案 0 :(得分:3)
如果你想根据一个整数的值调用一个函数,你最好不要写一个指向你的函数的指针数组,并使用你的整数索引到数组中。
void execcall0(int x);
void execcall1(int x);
void execcall2(int x);
/* Array of pointers to void functions taking an int parameter. */
void (*apfn[])(int) =
{
execcall0,
execcall1,
execcall2,
};
int main()
{
int i;
for (i = 0; i < 3; ++i) {
(apfn[i])(1);
}
}
请记住在编制索引之前检查边界条件!
答案 1 :(得分:2)
您可以使用数组来存储函数,并修改宏:
#include <stdio.h>
#define calling(m, j) exec_funcs[m](j)
void execcall0 (int x) {
printf("called 0 with arg %d\n", x);
}
void execcall1 (int x) {
printf("called 1 with arg %d\n", x);
}
void execcall2 (int x) {
printf("called 2 with arg %d\n", x);
}
void (*exec_funcs[3])(int) = { execcall0, execcall1, execcall2 };
int main () {
int i = 0;
for (i = 0; i < 3; i++) {
calling(i, 1);
}
}
但是,你真的不需要一个宏。