温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言中函数参数的省略号有什么用

发布时间:2021-08-27 18:15:58 来源:亿速云 阅读:233 作者:chen 栏目:编程语言

这篇文章主要讲解了“C语言中函数参数的省略号有什么用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C语言中函数参数的省略号有什么用”吧!

C++允许定义形参个数和类型不确定的函数。例如,C语言中的标准函数printf便使用这种机制。在声明不确定形参的函数时,形参部分可以使用省略号“…”代替。“…”告诉编译器,在函数调用时不检查形参类型是否与实参类型相同,也不检查参数个数。

例如:

void ConnectData(int i,...)

在上面的代码中,编译器只检查第一个参数是否为整型,而不对其他参数进行检查。

对于可变参数的函数,需要进行特殊的处理。首先需要引用 <stdarg.h> 头文件,然后利用va_list类型和va_start、va_arg、va_end 3个宏读取传递到函数中的参数值。

这几个宏的定义如下(在 ANSI C 中):

type va_arg( va_list arg_ptr, type );
void va_end( va_list arg_ptr );
void va_start( va_list arg_ptr, prev_param );   

说明如下:
va_start 
sets arg_ptr to the first optional argument in the list of arguments passed to the function. The argument arg_ptr must have va_list type. The argument
prev_param is the name of the required parameter immediately preceding the first optional argument in the argument list. If prev_param is declared with the register storage class, the macro’s behavior is undefined. va_start must be used before va_arg is used
for the first time.
【 va_start函数将参数arg_ptr设置为可变参数列表的第一个参数。参数arg_ptr的类型必须为va_list。参数prev_param是在可变参数列表之前的那一个参数。(也就是说在
ANSI C 中,如果一个函数有可变参数,那么在该可变参数前必须有一个明确定义的参数,否则无法调用函数 va_start ,例如函数 int add(int i,...)是合法的,而函数 int add(...)是不合法的。)】

va_arg 
retrieves a value of type from the location given by arg_ptr and increments arg_ptr to point to the next argument in the list, using the size of type
to determine where the next argument starts. va_arg can be used any number of times within the function to retrieve arguments from the list.
【 va_arg函数将返回 arg_ptr 所指位置的值,并将 arg_ptr 指向下一个参数 】
va_end
After all arguments have been retrieved, va_end resets the pointer to NULL. 

示例代码:
#include<cstdarg>
#include<iostream>
using namespace std;

int add(int pre,...)  //求和函数
{
    va_list arg_ptr;

    int sum=0;
    int nArgValue;

    sum+=pre;

    va_start(arg_ptr,pre);
    do
    {
        nArgValue=va_arg(arg_ptr,int);
        sum+=nArgValue;
        
    }while(nArgValue!=0);   //自定义结束条件是输入参数为0

    va_end(arg_ptr);

    return sum;
}
int main()
{
   cout<<add(1,2,3,0)<<endl;  //必须以0结尾,因为参数列表结束的判断条件是读到0停止
   return 0;

}

感谢各位的阅读,以上就是“C语言中函数参数的省略号有什么用”的内容了,经过本文的学习后,相信大家对C语言中函数参数的省略号有什么用这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI