3

va_arg这是在下面著名的链接中所说的:

http://www.cplusplus.com/reference/cstdarg/va_arg/

Notice also that va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list). The function should be designed in such a way that the number of parameters can be inferred in some way by the values of either the named parameters or the additional arguments already read.

除此之外,在我读到的一本一般的书中va_arg,所有示例都确保fixed参数之一始终是我们将要传递的变量参数的数量/计数。这个计数用于循环中前进va_arg到下一项,并且循环条件(使用计数)确保它在va_arg检索变量列表中的最后一个参数时退出。这似乎证实了网站上的上述段落"the function should be designed in such a way........" (above)

所以直截了当地说,va_arg有点愚蠢。但在从该网站获取的以下示例中va_endva_arg突然看起来很聪明。当到达类型变量参数列表的末尾时char*,它返回一个 NULL 指针。怎么会这样?我链接的最上面的一段清楚地说明了

"va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list"

此外,下面的程序中没有任何内容可以确保在越过变量参数列表的末尾时应该va_arg返回一个 NULL 指针。那么为什么会在列表的末尾返回一个 NULL 指针呢?

/* va_end example */
#include <stdio.h>      /* puts */
#include <stdarg.h>     /* va_list, va_start, va_arg, va_end */

void PrintLines (char* first, ...)
{
  char* str;
  va_list vl;

  str=first;

  va_start(vl,first);

  do {
    puts(str);
    str=va_arg(vl,char*);
  } while (str!=NULL);

  va_end(vl);
}

int main ()
{
  PrintLines ("First","Second","Third","Fourth",NULL);
  return 0;
}    

输出

First

Second

Third

Fourth

节目源链接

4

1 回答 1

11

当到达类型变量参数列表的末尾时char *,它返回一个NULL指针。怎么会这样?

因为传递给函数的最后一个参数确实是NULL

PrintLines("First", "Second", "Third", "Fourth", NULL);
于 2013-05-07T17:26:27.220 回答