gpt4 book ai didi

c++ - 函数参数列表中的三个点是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 13:23:45 26 4
gpt4 key购买 nike

我遇到了这样的函数定义:

char* abc(char *f, ...)
{
}

三个点是什么意思?

最佳答案

这些类型的函数称为可变参数函数 (Wikipedia link)。他们使用省略号(即三个点)来表示函数可以处理的参数数量可变。您可能使用过此类函数的一个地方(可能没有意识到)是使用各种 printf 函数,例如(来自 ISO 标准):

int printf(const char * restrict format, ...);

省略号允许您在事先不知道参数数量的情况下创建函数,并且您可以使用 stdargs.h 函数(va_startva_argva_end) 来获取具体的参数。

你必须知道你提取的参数的类型,并且有一些方法来决定你何时完成。 printf 函数使用格式字符串(对于类型和计数)执行此操作,而我下面的示例代码始终假定 const char * 作为具有标记值的类型 NULL决定完成。

此链接here关于在 printf 中使用可变参数列表有一篇很好的论文。


例如,以下程序包含一个函数 outStrings(),它允许您打印任意数量的字符串:

#include <stdio.h>
#include <stdarg.h>

void outStrings(const char *strFirst, ...) {
// First argument handled specially.

printf("%s", strFirst);
va_list pArg;
va_start(pArg, strFirst);

// Just get and process each string until NULL given.

const char *strNext = va_arg(pArg, const char *);
while (strNext != NULL) {
printf("%s", strNext);
strNext = va_arg(pArg, const char *);
}

// Finalise processing.

va_end(pArg);
}

int main(void) {
char *name = "paxdiablo";
outStrings("Hello, ", name, ", I hope you're feeling well today.\n", NULL);
}

关于c++ - 函数参数列表中的三个点是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/599744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com