2

I'm reading Johnson M. Hart Windows System programming. He has a method that makes use of the va_start standard c method. In the below sample can someone explain why the Handle hOut is being passed to va_start?

BOOL PrintStrings (HANDLE hOut, ...)

/* Write the messages to the output handle. Frequently hOut
    will be standard out or error, but this is not required.
    Use WriteConsole (to handle Unicode) first, as the
    output will normally be the console. If that fails, use WriteFile.

    hOut:   Handle for output file. 
    ... :   Variable argument list containing TCHAR strings.
        The list must be terminated with NULL. */
{
    DWORD msgLen, count;
    LPCTSTR pMsg;
    va_list pMsgList;   /* Current message string. */
    va_start (pMsgList, hOut);  /* Start processing msgs. */
    while ((pMsg = va_arg (pMsgList, LPCTSTR)) != NULL) {
        msgLen = lstrlen (pMsg);
        if (!WriteConsole (hOut, pMsg, msgLen, &count, NULL)
                && !WriteFile (hOut, pMsg, msgLen * sizeof (TCHAR), &count, NULL)) {
            va_end (pMsgList);
            return FALSE;
        }
    }
    va_end (pMsgList);
    return TRUE;
}
dcrearer
  • 1,972
  • 4
  • 24
  • 48
  • 1
    void va_start (va_list ap, paramN); Initialize a variable argument list Initializes ap to retrieve the additional arguments after parameter paramN. – dcrearer Nov 08 '15 at 22:14
  • Because the C standard requires it: the second argument to [`va_start`](http://en.cppreference.com/w/c/variadic/va_start) must be the last named parameter of the function. – Kninnug Nov 08 '15 at 22:15
  • @Kninnug could another value be used instead of the HANDLE? – dcrearer Nov 08 '15 at 22:17
  • The `...` in the function signature means that the function can accept any number of arguments following `hOut`, and `va_start` and `va_arg` are how the function is able to access those arguments. – Jonathan Potter Nov 08 '15 at 22:24

1 Answers1

1

va_start is a macro that pulls of variadic parameters. It works by being given the parameter immediately before the first variadic parameter. The point is that va_start needs to know where the variadic parameters can be found. They are found immediately after the last named parameters. Hence the use of hOut.

Some details on how variadic parameters are typically implemented:

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490