How can one print a size_t variable portably using the printf family?

前端 未结 12 964
时光说笑
时光说笑 2020-11-22 05:40

I have a variable of type size_t, and I want to print it using printf(). What format specifier do I use to print it portably?

In 32-bit ma

12条回答
  •  悲哀的现实
    2020-11-22 05:56

    Extending on Adam Rosenfield's answer for Windows.

    I tested this code with on both VS2013 Update 4 and VS2015 preview:

    // test.c
    
    #include 
    #include  // see the note below
    
    int main()
    {
        size_t x = 1;
        SSIZE_T y = 2;
        printf("%zu\n", x);  // prints as unsigned decimal
        printf("%zx\n", x);  // prints as hex
        printf("%zd\n", y);  // prints as signed decimal
        return 0;
    }
    

    VS2015 generated binary outputs:

    1
    1
    2

    while the one generated by VS2013 says:

    zu
    zx
    zd

    Note: ssize_t is a POSIX extension and SSIZE_T is similar thing in Windows Data Types, hence I added reference.

    Additionally, except for the follow C99/C11 headers, all C99 headers are available in VS2015 preview:

    C11 - 
    C11 - 
    C11 - 
    C99 - 
    C11 - 
    

    Also, C11's is now included in latest preview.

    For more details, see this old and the new list for standard conformance.

提交回复
热议问题