开发者

Why doesn't %zd printf format work in VS2010?

Following piece of my code does not print the value in visual studio.

int main() { 
    intptr_t P = 10;
    printf("test value is %zd",P);
    return 0;
}

OUTPUT:

test value is zd

I expect the the above code print

test v开发者_如何学Pythonalue is 10

i am using intptr_t instead of integer so as to make the code to adjust in both the 32 bit and 64 bit architecture.


The z prefix isn't defined in Microsoft's version of printf. I think the I prefix might work. See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx


Although the z length specifier is supported in C99, Visual Studio 2010 does not support C99, and instead conforms to an older version of C that was missing the z length specifier. As an extension, VS2010 does support the I length specifier instead for size_t, but this is not portable to other platforms.

I would recommend using an unsigned long long with the %llu specifier instead; the overhead is minimal and it's portable to C99 platforms as well.


For portable code, #include <inttypes.h> and use PRIdPTR in your printf format string.

printf("test value is %" PRIdPTR, P);

The Wikipedia page for inttypes.h has a link to a version of that file that will work with Visual C++, and would probably work with VS2010 as well (if Microsoft didn't add an inttypes.h).

PRIdPTR is for intptr_t, PRIuPTR is for uintptr_t.


Visual C++, as of VS 2013, does not support %z. If you want future versions to support it then vote on this bug:

https://connect.microsoft.com/VisualStudio/feedback/details/806338/vc-printf-and-scanf-should-support-z


To print size_t you need to use %Iu in VS and %zu in gcc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜