Hello...

I'm learning win32 api programming, and I can't figure out how the vsprintf
(va_list, va_start, va_end) function works in the following code:

/*-----------------------------------------------------
   SCRNSIZE.C -- Displays screen size in a message box
                 (c) Charles Petzold, 1998
  -----------------------------------------------------*/

#include <windows.h>
#include <tchar.h>     
#include <stdio.h>     

int CDECL MessageBoxPrintf (TCHAR * szCaption, TCHAR * szFormat, ...)
{
     TCHAR   szBuffer [1024] ;
     va_list pArgList ;

          // The va_start macro (defined in STDARG.H) is usually equivalent to:
          // pArgList = (char *) &szFormat + sizeof (szFormat) ;

     va_start (pArgList, szFormat) ;

          // The last argument to wvsprintf points to the arguments

     _vsntprintf (szBuffer, sizeof (szBuffer) / sizeof (TCHAR), 
                  szFormat, pArgList) ;

          // The va_end macro just zeroes out pArgList for no good reason

     va_end (pArgList) ;

     return MessageBox (NULL, szBuffer, szCaption, 0) ;
}

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    PSTR szCmdLine, int iCmdShow) 
{
     int cxScreen, cyScreen ;

     cxScreen = GetSystemMetrics (SM_CXSCREEN) ;
     cyScreen = GetSystemMetrics (SM_CYSCREEN) ;
     MessageBoxPrintf (TEXT ("ScrnSize"), 
                       TEXT ("The screen is %i pixels wide by %i pixels high."),
                       cxScreen, cyScreen) ;
     return 0 ;
}

Could anyone explain how does this function work?
Especially this line:

_vsntprintf (szBuffer, sizeof (szBuffer) / sizeof (TCHAR), szFormat, pArgList) ;

Edited 5 Years Ago by ak24: n/a

This link has an example of how that function works. If you know how sprintf() works then you're nearly home with vsprintf(). Then if you read this thread you will see that the second parameter to vnsprintf() is the number of characters in the buffer. When compiled for UNICODE sizeof(TCHAR) will be greater than 1, the actual size will depend on the operating system you are using. MS-Windows sizeof(wchar_t) is 2, but *nix it is 4.

Thank you. I'm beginning to understand how it works.

Edited 5 Years Ago by ak24: n/a

This article has been dead for over six months. Start a new discussion instead.