C / C ++ language function parameters in the "..." The role of (stdarg.h)

With Linux "man manual" in the printf function declaration, for example, to talk about my little understanding of the variable parameters of the C language functions.

printf function declaration is as follows: int printf (const char * format, ...); Typically, in this form of the function parameter list declaration function requires at least one common parameter, the latter does not represent ellipsis omitted, but the function prototypes portion.

Implementation of the variable parameter: C language header files "stdarg.h" provides a data type and the three parameters va_list macros (va_start, va_arg and va_end). Va_list wherein the following statement: typedef char * va_list; va_start type va_list vp such that points to the first optional parameter, va_arg returns the current parameter and the parameter list of points to the next parameter vp parameter list, va_end the index pointer is NULL vp .

Below I have written some C / C ++ code to validate or more ways:

Example:

// 求参数列表中可变参数的和(可指定个数)
//#include <iostream>
//#include <cstdarg>
#include <stdio.h>
#include <stdarg.h>

//求n个可变参数的和 
int sum(int n, int j, ...)
{
    printf ("n = %d, j = %d\n", n, j);
    int s = 0;
    int i = 0;
    va_list vp;
    va_start(vp, j);  //使得vp指向第一个可选参数
    for(i = 0; i < n; ++i)
    {
        int va = va_arg(vp, int);
        //s += va_arg(vp, int);
        s += va;
        printf ("vp_arg() = %d\n", va);
        printf ("s = %d\n", s);
    }
    va_end(vp);
    return s;
}

int main()
{    
    int j = sum(4,3,2,3,4,5,6);
    printf ("j = %d\n", j);
    
    return 0;
}

result:

n = 4, j = 3
vp_arg () = 2
p = 2
vp_arg () = 3
p = 5
vp_arg () = 4
p = 9
vp_arg () = 5
s = 14
j = 14

analysis:

Function sum function is to find the first n and the variable parameter, the function call to the "sum (4,3,2,3,4,5,6)" returns the value should be the first four of the variable parameter and, that is, 2 + 3 + 4 + 5 = 14.
Output Results: j = 14

 

Published 288 original articles · won praise 291 · Views 250,000 +

Guess you like

Origin blog.csdn.net/u012206617/article/details/104007283