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;
}
4
  • 1
    void va_start (va_list ap, paramN); Initialize a variable argument list Initializes ap to retrieve the additional arguments after parameter paramN. Commented Nov 8, 2015 at 22:14
  • Because the C standard requires it: the second argument to va_start must be the last named parameter of the function. Commented Nov 8, 2015 at 22:15
  • @Kninnug could another value be used instead of the HANDLE? Commented Nov 8, 2015 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. Commented Nov 8, 2015 at 22:24

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

9 Comments

can you please expound a little on this statement "va_start is a macro that pulls of variadic parameters"? I very new to C and seeking some insight.
@DavidHeffernan I'm not sure that dupe really explains what varargs are which seems to be the OP's problem.
@JonathanPotter The question can only really be interpreted as though asker already knows what varargs are.
I understand variadics. Its just unclear why the HANDLE is used.
Did you read the dupe question?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.