printf conversion specifier for _Bool?

前端 未结 5 878
猫巷女王i
猫巷女王i 2021-02-19 09:04

With printf(), I can use %hhu for unsigned char, %hi for a short int, %zu for a size_t

5条回答
  •  佛祖请我去吃肉
    2021-02-19 09:32

    As you stated in a comment to @Jack, "6.3.1.1p1 says that the conversion rank of _Bool is less than the rank of all other standard integer types".

    In a call to printf, a char or short will be promoted and passed on the stack as an int (or an unsigned int), so I would think that using %d as a format specifier would be fine. That also means that you don't need the explicit cast to int, because that will happen automatically.

    The only possible issue would be with how the compiler represents a _Bool, something that it probably implementation defined and could vary from one compiler to another. I see two likely implementations -- 0 and 1 or 0 and -1.

    For the ultimate in portability, follow @user325181's answer and use a ternary to choose between two options. Either integers (which the compiler may optimize away) or strings.

    Edit: As reported in other answers, a _Bool is defined as an unsigned integral type that can store either 0 or 1. Because of that, and the fact that it will be promoted to an unsignedint when passed to printf(), I would say that %u%d is the most appropriate specifier.

提交回复
热议问题