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

前端 未结 9 2570
醉梦人生
醉梦人生 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 14:51

    The effective type underlying size_t is implementation dependent. C Standard defines it as the type returned by the sizeof operator; aside from being unsigned and a sort of integral type, the size_t can be pretty much anything which size can accommodate the biggest value expected to be returned by sizeof().

    Consequently the format string to be used for a size_t may vary depending on the server. It should always have the "u", but may be l or d or maybe something else...

    A trick could be to cast it to the biggest integral type on the machine, ensuring no loss in the conversion, and then using the format string associated with this known type.

提交回复
热议问题