Since ANSI C99 there is _Bool
or bool
via stdbool.h
. But is there also a printf
format specifier for bool?
I mean something like in that pseudo code:
bool x = true;
printf("%B\n", x);
which would print:
true
Since ANSI C99 there is _Bool
or bool
via stdbool.h
. But is there also a printf
format specifier for bool?
I mean something like in that pseudo code:
bool x = true;
printf("%B\n", x);
which would print:
true
There is no format specifier for bool
types. However, since any integral type shorter than int
is promoted to int
when passed down to printf()
's variadic arguments, you can use %d
:
bool x = true;
printf("%d\n", x); // prints 1
But why not:
printf("Your boolean variable is: %s", x ? "true" : "false");
instead?
printf("%s", x ? "true" : "false");
would fix the issue. –
Committeewoman printf("%s", x ? "true" : "false");
is better that printf(x ? "true" : "false");
- you are in total control of the format string here so there is no danger that it'll get something like "%d"
which would cause problems. The fputs
, on the other hand, is a better option. –
Midsection %d
give -1 or 0. And%ld
give MAX_INT. –
Crosscut fputs(x ? "true" : "false", stdout);
better than printf("%s", x ? "true" : "false");
and the latter better than printf(x ? "true" : "false");
? –
Obligatory char *
to printf()
is considered bad practice because it's really supposed to be a format string, and an unescaped percent sign might cause your program to blow up (see here for more). Thus, printf("%s", ...)
is safer. If you're not doing any actual formatting to begin with, the printf
family of functions is overkill and puts()
(or fputs()
if you need to print to stderr
) is preferable because it's more efficient/concise. –
Ralleigh false
is zero, and true
is "non-zero." Based on implementation, it may print 9, 24, or even a negative value, like -1. If I'm correct, you may want to update your comment to say "prints non-zero" so as to further discourage that unfavorable method. –
Pipit fputs
"even better"? I'm always looking for ways to improve my C. Under what circumstances should I use fputs
instead of printf
? –
Panel printf()
by fputs(stdout)
whenever possible, so efficiency is the same. –
Bricole There is no format specifier for bool
. You can print it using some of the existing specifiers for printing integral types or do something more fancy:
printf("%s", x?"true":"false");
bool
type in C, just not in the C89 edition -- it's part of the C99 language spec. There's a new keyword _Bool
, and if you include <stdbool.h>
, then bool
is a synonym for _Bool
. –
Sedan 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 <stdio.h>
#include <printf.h>
#include <stdbool.h>
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)
In the tradition of itoa()
:
#define btoa(x) ((x)?"true":"false")
bool x = true;
printf("%s\n", btoa(x));
btoa
is "binary string to base 64 string" in non-standard JavaScript (Gecko and WebKit), so you might want to use a different name. –
Teraterai "true\0false"[(!x)*5]
:-) –
Midsection &
:-) –
Pentup "false\0true"[x*5]
is a touch simpler –
Filterable !!x*5
. –
Pentup *
, bool
is promoted to int
with the value 1
or 0
, so it's safe. As long as x
remains a bool
anyway. I see your point. –
Filterable !!x*6
, now that false is one char longer than true? –
Estate To just print 1 or 0 based on the boolean value I just used:
printf("%d\n", !!(42));
Especially useful with Flags:
#define MY_FLAG (1 << 4)
int flags = MY_FLAG;
printf("%d\n", !!(flags & MY_FLAG));
!!
might get optimized away –
Reverse !!(flags & MY_FLAG)
could get replaced with (flags & MY_FLAG)
, but a non-broken compiler would not be able to optimize away !!
unless it could prove that the operand couldn't have any value other than 0 or 1. –
Viperous If you like C++ better than C, you can try this:
#include <ios>
#include <iostream>
bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;
I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like
printf("%s\n", "false\0true"+6*x);
"false\0true"+6*x
really did. If you work in a project with other people, or just in a project whit a codebase you want to understand x years later, constructions like this is to be avoided. –
Obligatory printf("%s\n","false\0true"+6*(x?1:0));
which is only... 5% less readable. –
Woods static inline char const *bool2str(_Bool b) { return "false\0true"+6*x; } int main(void) { printf("%s != %s", bool2str(false), bool2str(true)); return 0; }
Same as with static inline char decimal2char(int d) { assert(d >= 0 && d <= 9); return '0' + d; }
; just wrap it in a descriptively named function and don't worry about it's readability. –
Elnoraelnore puts( tf ? "true" : "false" );
as a conditional-move instruction, not a branch. On architectures where it would be more efficient, they can generally replace that with something like (char*)((uintptr_t)option1^ (((uintptr_t)x-1U)&((uintptr_t)option1^(uintptr_t)option2)))
on targets where that's more efficient. That code is a maintenance nightmare. –
Morey "false\0true"+6 *!!a
... ;) FWIW, a godbolt link that illustrates @Davislor's point. –
Bakker © 2022 - 2024 — McMap. All rights reserved.