c中具有不同类型参数的可变参数函数 [英] variadic functions with different types of arguments in c

查看:66
本文介绍了c中具有不同类型参数的可变参数函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在C语言中是否有可能创建一个采用不同类型参数的可变参数函数.即

I was wondering if it's possible in C to create a variadic function that takes different types of arguments. i.e.

void fillDatabase(char* name, int age){
  writeToDatabase(name, age);
}

int main(){
  fillDatabase("Paul", 19);
  fillDatabase("Herbert");
}

在这里,我试图用名称和年龄填充数据库.但是也可以只用一个名字而不用年龄来填充它.所以我想知道是否可以为此使用相同的功能,或者是否必须编写两个不同的功能?

Here I am trying to fill up a database with names and ages. But it's also possible to fill it up with only a name and no age. So I am wondering if I could use the same function for that or if I have to write two different ones?

在线我只能找到variadic的示例具有相同类型参数的函数.

Online I could only find examples for variadic functions with the same type of arguments.

提前谢谢!

推荐答案

在C99中,可变参数函数使用 stdarg(3)操作(通常实现为宏,扩展为特定于编译器的神奇的东西,例如GCC内置函数).第一个参数应具有某种固定的已知类型,并通常确定如何获取其他参数.在当今的几种ABI中,可变参数函数传递不使用寄存器,因此效率不如固定arity函数调用.

In C99, variadic functions use stdarg(3) operations (generally implemented as macros expanding to compiler-specific magical stuff, e.g. GCC builtins). The first arguments should have some fixed known type, and generally determinates how the other arguments are fetched; in several today's ABIs, variadic function argument passing don't use registers so is less efficient than fixed arity function calls.

对于您来说,您最好具有多个功能.为了获得灵感,sqlite具有多个打开函数.

In your case, you'll better have several functions. For inspiration sqlite has several open functions.

请注意,POSIX使用一个 last 可选参数定义了某些功能,尤其是

Notice that POSIX defines some function with one last optional argument, in particular open(2). This is probably implemented as having a function whose last argument can be not supplied.

您可以阅读 ABI 规范和

You could read the ABI specification and the calling conventions specific to your implementation.

顺便说一句,缺少函数重载(例如在C ++中)可以理解为C的优点(函数名-这是名称处理.另请参阅动态链接

BTW, lack of function overloading (like in C++) can be understood as an advantage of C (the function name -which is the only thing the linker care about, at least on Linux & Unix- determines its signature). Hence C++ practically needs name mangling. Read also about dynamic linking and dlopen

这篇关于c中具有不同类型参数的可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆