What's the correct way to use printf to print a size_t?

前端 未结 3 1195
礼貌的吻别
礼貌的吻别 2020-11-22 00:18

Size_t is defined as an unsigned integer, but the size of it depends on whether you\'re on a 32 or 64-bit machine. What\'s the correct and portable

3条回答
  •  自闭症患者
    2020-11-22 00:57

    I think that the C++ answer is:

    std::size_t n = 1;
    std::cout << n;
    

    For C-style IO it's a little more complicated. In C99 they added the z length modifier for size_t values. However, previous to TR1 this is not supported so you are left with casting to a specific size like:

    std::size_t n = 1;
    std::printf("%lu\n", static_cast(n));
    

    Then again, unsigned long long isn't really supported by C++ anyway so the above will work fine since unsigned long is the largest legal integral type. After TR1 you can use %zu safely for size_t values.

提交回复
热议问题