Clean code to printf size_t in C++ (or: Nearest equivalent of C99's %z in C++)

前端 未结 9 2571
醉梦人生
醉梦人生 2020-12-07 14:20

I have some C++ code that prints a size_t:

size_t a;
printf(\"%lu\", a);

I\'d like this to compile without warnings on both 32

9条回答
  •  無奈伤痛
    2020-12-07 15:07

    C++11

    C++11 imports C99 so std::printf should support the C99 %zu format specifier.

    C++98

    On most platforms, size_t and uintptr_t are equivalent, in which case you can use the PRIuPTR macro defined in :

    size_t a = 42;
    printf("If the answer is %" PRIuPTR " then what is the question?\n", a);
    

    If you really want to be safe, cast to uintmax_t and use PRIuMAX:

    printf("If the answer is %" PRIuMAX " then what is the question?\n", static_cast(a));
    

提交回复
热议问题