What is the printf format specifier for bool?

前端 未结 8 767
有刺的猬
有刺的猬 2020-11-28 17:13

Since ANSI C99 there is _Bool or bool via stdbool.h. But is there also a printf format specifier for bool?

I mean

8条回答
  •  悲哀的现实
    2020-11-28 17:56

    ANSI C99/C11 don't include an extra printf conversion specifier for bool.

    But the GNU C library provides an API for adding custom specifiers.

    An example:

    #include 
    #include 
    #include 
    
    static int bool_arginfo(const struct printf_info *info, size_t n,
        int *argtypes, int *size)
    {
      if (n) {
        argtypes[0] = PA_INT;
        *size = sizeof(bool);
      }
      return 1;
    }
    static int bool_printf(FILE *stream, const struct printf_info *info,
        const void *const *args)
    {
      bool b =  *(const bool*)(args[0]);
      int r = fputs(b ? "true" : "false", stream);
      return r == EOF ? -1 : (b ? 4 : 5);
    }
    static int setup_bool_specifier()
    {
      int r = register_printf_specifier('B', bool_printf, bool_arginfo);
      return r;
    }
    int main(int argc, char **argv)
    {
      int r = setup_bool_specifier();
      if (r) return 1;
      bool b = argc > 1;
      r = printf("The result is: %B\n", b);
      printf("(written %d characters)\n", r);
      return 0;
    }
    

    Since it is a glibc extensions the GCC warns about that custom specifier:

    $ gcc -Wall -g    main.c   -o main
    main.c: In function ‘main’:
    main.c:34:3: warning: unknown conversion type character ‘B’ in format [-Wformat=]
       r = printf("The result is: %B\n", b);
       ^
    main.c:34:3: warning: too many arguments for format [-Wformat-extra-args]
    

    Output:

    $ ./main
    The result is: false
    (written 21 characters)
    $ ./main 1
    The result is: true
    (written 20 characters)
    

提交回复
热议问题