I have the following helper function:

inline void DebugMessage(const TCHAR* fmtstr, ...)
{
        va_list args;
        va_start(args, fmtstr);

        TCHAR buffer[256];
        StringCbVPrintf(buffer, 256, fmtstr, args);
        OutputDebugString(buffer);

        va_end(args);
}

And I call it twice like so:

DebugMessage(_T("Test %d\n", 1)); // incorrectly closed _T()
DebugMessage(_T("Test %d\n"), 1); // correctly closed _T()

I get the following output:

Test 0
Test 1

The 2nd case works as expected. I am confused why the first case functions at all, rather than being an error?

有帮助吗?

解决方案

_T is not a function, it's a macro that (in a Unicode build) expands to L ## x. The misplaced bracket doesn't cause a compile error, it simply changes which parts of the line gets consumed by the macro.

The macro only takes one parameter (x) and so in the first case, with the incorrect closure, the second parameter (1) is simply discarded, and the number you get in your output is simply a result of random data on the stack.

Note that by default, VS 2012 will issue a C4002 warning about this (too many actual parameters for macro) so you may want to check that you have warnings enabled properly.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top