C ++ variable parameter transfer function

Variable parameters defined function, use the following macros:

  • va_start (ap, farg): initialize a variable va_list ap, farg first parameter
  • va_arg (ap, type): a type of parameter type acquiring (lower)
  • va_end (ap): End Use ap

C language written in the form of variable parameters function like this:

#include <stdarg.h>
int sum(int cnt,...) {
    int sum = 0;
    int i;
    va_list ap;
    va_start(ap, cnt);
    for(i = 0; i < cnt; ++i)
        sum += va_arg(ap, int);
    va_end(ap);
    return sum;
}

Variable parameters defined function, use the following macros:

  • va_start (ap, farg): initialize a variable va_list ap, farg first parameter
  • va_arg (ap, type): a type of parameter type acquiring (lower)
  • va_copy (ap): used to copy parameter list
  • va_end (ap): ap finished using
    these macros in general stdarg.hthere.
typedef char * va_list;
#define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1)  )
#define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v)  )
#define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t))  )
#define va_end(ap) ( ap = (va_list)0 )

Note:  The above macro definitions vary with different systems and different processor architectures differ

_INTSIZEOF macro
_INTSIZEOF this macro bit more difficult to understand the operational significance, at first glance thought it was the number of type int length represents, in fact, the result of its operations out of the length of the aligned according to an int. Such as int type is 4 bytes, _INTSIZEOF (1), _ INTSIZEOF (2), _ INTSIZEOF (3), _ a result INTSIZEOF (4) is 4, _INTSIZEOF (5), _ INTSIZEOF (6), _ INTSIZEOF (7), _ INTSIZEOF (8) the result is 8, which is a parameter passing mode the x86 architecture CPU, 32 bits, i.e., 4-byte alignment.

A few notes

  • Indefinite function parameters have at least one fixed parameter because it is used to initialize the va_list, such cnt parameter code above the sum function, it also indicates the number of parameters passed.

Common way

Variable function parameters most commonly used format string, a more common scenario is that we want to export some log messages, but can not be output directly in the console, you need to write a log function to format the log message and output. Then we can use vsprintf function:

void log(const char *format, ...) {
    char buf[MAX_BUF_SIZE];
    va_list ap;
    va_start(ap, format);
    vsprintf(buf, format, ap);
    OUTPUT(buf);
}

The first two parameters the same meaning and the first two parameters of vsprintf function sprintf, but the back of the uncertain parameters replaced by va_list type of the parameter list, which is what we used to define your own formatting functions.

 

https://www.cnblogs.com/luzhlon/p/7087080.html

Guess you like

Origin www.cnblogs.com/feng9exe/p/11016394.html