Application C language special functions

1. va_list correlation function of learning:

va_list variable parameter is a pointer type definition.

va_list used as follows:

1) First define a variable of type va_list has a function, variable parameter is a pointer to a pointer.

2) First define a variable of type va_list has a function, variable parameter is a pointer to a pointer.

3) Then va_arg returns a variable parameter, the second parameter is the type parameter of va_arg you want to return (if a plurality of variable parameters, in turn call va_arg get the parameters).

4) va_end macro variable parameters to obtain the final end use.

In use va_list should pay attention to the problem:

1) the type and number of variable parameters is controlled entirely by the code, it can not intelligently identify the number and type of different parameters.

2) If we do not need 11 Xiangjie each parameter, simply copy the list to a variable buffer, you can use vsprintf function.

3) because the compiler to check the function prototype variable parameters are not stringent enough, troubleshooting unfavorable programming, is not conducive to us to write high-quality code.
Coding:
#include "stdarg.h"
#include <iostream>
#include <stdio.h>

static char buf[512];
int sum(char* msg, ...);

int main(void)
{
    int total = 0;
    char str[] = "%dhello%dworld!%d";
    total = sum(str, 1, 2, 3);
    std::cout << "total = " << total <<:: endl STD;
     return  0 ; 
} 

int SUM ( char * MSG, ...) 
{ 
    va_list vaList; // define a variable of type va_list having variable parameter is a pointer to a pointer. 
    the va_start (vaList, MSG); // first variable parameter points to the address list, the address is automatically increased, and the second parameter bit fixed value 
    STD :: MSG COUT << << STD :: endl;
     int sumNum = 0 ;
     int STEP, I; 

    vsnprintf (buf, the sizeof (buf), MSG, vaList); 

    for (I = 0 ; I < 30 ; I ++ ) { 
        the printf ( " % C " , buf [I]); 
    }
     The while ( 0 ! = (STEP = the va_arg (vaList, int ))) // the va_arg The first argument is the address of the variable parameter, the second parameter is the type of parameters passed, then the return value is the address va_list value, type, and $ 
    {                           // the va_arg get the next pointer
         // not equal to 0, there are parameter may take the va_list 
        sumNum + = STEP; 
    } 
    to va_end (vaList); // end variable argument lists 
    return sumNum; 
}

Reference:

a. https://www.cnblogs.com/qiwu1314/p/9844039.html

Guess you like

Origin www.cnblogs.com/uestc-mm/p/11622646.html