c - 函数返回它自己

标签 c

<分区>

typedef logs_t(*logs_t)(char *);

logs_t logs(char *s) {
    printf("%s", s);
    fflush(0);
    return &logs;
}

错误:

log.c:1:17: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
typedef logs_t(*logs_t)(char *);
                ^
log.c:1:9: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
typedef logs_t(*logs_t)(char *);
~~~~~~~ ^
log.c:1:15: fatal error: function cannot return function type 'int (char *)'
typedef logs_t(*logs_t)(char *);
              ^
2 warnings and 1 error generated.

我在这里想要实现的是将调用链接到logs:

logs("a")("b");

最佳答案

你不能在 C 中做这样的递归类型定义。但是相互递归是可能的 - 你可以通过返回一个包含指向函数的指针作为成员的 struct 来链接:

#include <stdio.h>

struct foo {
    struct foo (*logs)(char *);
};

struct foo logs(char *arg) {
    puts(arg);
    return (struct foo){ logs };
}

int main() {
    logs("foo").logs("bar");
}

但是,这对的情况几乎没有用;也不在任何其他一般情况下,因为 foo 不会作为 this 传入,所以您最终只需要输入 . ;

我认为它仅在函数不会总是返回自身的情况下才有用;)

也许您想要使用可变参数

关于c - 函数返回它自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749562/

相关文章:

c - c中的字符串反转

c - 如何使用 C 中的 Vala 对象/方法?

在 C 中比较 ""和 ""

c - 在C中获取 "char *namelist[]"中项目的总数

c++ - 内存移动与向后复制

堆栈上的 C 数组

c - C 中的信号量和死锁

c - 替换字符

c - 哪个 boost 宏允许我在程序中插入可变数量的语句

C: nftw() 的奇怪行为