문제

This is what has been said about va_arg in the reputed link below:

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.

In addition to that, in the so-so book from which I read about va_arg,all examples have made sure that one of the fixed arguments is always the number/count of variable arguments we would be passing.And this count is used in a loop that advances va_arg to the next item,and the loop condition (using the count) makes sure that it exits when va_arg retrieves the last argument in the variable list.This seems to corroborate the above paragraph from the site which says that "the function should be designed in such a way........" (above).

So in blunt words, va_arg is kinda dumb.But in the following example taken from that website for va_end,va_arg suddenly seems to act smartly.When the end of a variable argument list of type char* is reached, it returns a NULL pointer. How is it so? The topmost paragraph I linked clearly states

"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"

and further,there is nothing in the following program that ensures that a NULL pointer should be returned when the end of the variable argument list is crossed.So how come va_arg returns a NULL pointer here at the end of the list?

/* 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;
}    

Output

First

Second

Third

Fourth

Program Source Link

도움이 되었습니까?

해결책

When the end of a variable argument list of type char * is reached, it returns a NULL pointer. How is it so?

Because the last argument passed to the function is indeed NULL:

PrintLines("First", "Second", "Third", "Fourth", NULL);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top