如何用C语言制作一个类似于Python的输出函数?

BMP*_*MPL 5 c python output

我正在开发一种名为 BPML 的自定义编程语言,我想尝试更新名为 的输出函数say()

C 中的最新版本:

void say(char *text) {
    printf("%s", text);
}
Run Code Online (Sandbox Code Playgroud)

Python 的最新版本:

def say(text):
    print(text, end = '')
Run Code Online (Sandbox Code Playgroud)

在 C 中,我希望它像 Python 的print()函数一样,只需在函数中输入变量即可,但在 C 中情况并非如此,因为您仍然必须使用适当类型的变量。

这就是为什么我在编写的程序中出现错误:

#include <stdio.h>

void say(char *text);

int main() {
    int number = 21;
    say(number);
}

void say(char *text) {
    // Output function
}
Run Code Online (Sandbox Code Playgroud)

错误:

P1.c:7:9: error: incompatible integer to pointer conversion passing 'int' to parameter of type 'char *' [-Werror,-Wint-conversion]
    say(number);
        ^~~~~~
Run Code Online (Sandbox Code Playgroud)

我仍然需要使用itoa()中的函数<stdlib.h>,但我没有想到,因为它在 CI 使用的版本中不可用。

那么是否有可能制作某种类似于Python函数行为方式的输出函数呢?

Ant*_*ala 5

C 没有重载,也没有函数模板。但您可以在 C11 及以上版本中通过宏和通用选择来选择合适的格式:

#include <stdio.h>

#define say(X) printf(_Generic((X),    \
                        double: "%f ", \
                        float:  "%f ", \
                        char *: "%s ", \
                        int:    "%d "  \
                ), (X));

int main(void) {
    say(21);
    say(21.5);
    say(21.5f);
    say("Hello world");
}
Run Code Online (Sandbox Code Playgroud)

这可以与 X 宏结合使用,轻松构建真正强大的结构:

#include <stdio.h>

// you can easily add new supported types here
#define SAY_FORMATS(X) \
    X(double, "%f")    \
    X(float,  "%f")    \
    X(char *, "%s")    \
    X(int,    "%d")
    
// add space after each item. Leading comma so that we do not
// need to have a dummy entry in the end. Unfortunately C 
// does not like trailing commas in _Generic. Thanks to 
// user694733 for the idea
#define GENERIC_ENTRY(Type, Format) \
    , Type: Format " "

#define say(X)                      \
     printf(_Generic((X)            \
         SAY_FORMATS(GENERIC_ENTRY) \
     ), (X))

int main(void) {
    say(21);
    say(21.5);
    say(21.5f);
    say("Hello world");
}
Run Code Online (Sandbox Code Playgroud)