printf conversion specifier for _Bool?

前端 未结 5 867
猫巷女王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:41

    There is no. Just handling it like an int by using %d or %i specifier.

    _Bool

    In C99, a new keyword, _Bool, is introduced as the new boolean type. In many aspects, it behaves much like an unsigned int, but conversions from other integer types or pointers always constrained to 0 and 1. Other than for other unsigned types, and as one would expect for a boolean type, such a conversion is 0 if and only if the expression in question evaluates to 0 and it is 1 in all other cases. The header stdbool.h provides macros bool, true and false that are defined as _Bool, 1 and 0, respectively.

    The first way to implement it that come from into mind is by using a char or(int8_t) an enum and with bit fields. But actually, it depends. It can be a typedef for an int(as I've mentioned, it's used, but is not recommend, subject to bugs) or char or unsigned int or an enum and #define that's commonly used.

    For exampe, Apple's implementation uses int,as you can see:

    #ifndef _STDBOOL_H_
    #define _STDBOOL_H_ 
    
    #define __bool_true_false_are_defined   1
    
    #ifndef __cplusplus
    
    #define false   0
    #define true    1
    
    #define bool    _Bool
    #if __STDC_VERSION__ < 199901L && __GNUC__ < 3
    typedef int _Bool;
    #endif
    
    #endif /* !__cplusplus */
    
    #endif /* !_STDBOOL_H_ */
    

    Others implementations:

    typedef int8_t _Bool;

    typedef enum { false = 0, true = 1 } bool;

    typedef unsigned char Boolean; typedef _Bool Boolean;

提交回复
热议问题