C Printing Boolean: What Gets Displayed?
Introduction
When printing boolean values in C , it's important to understand the specified behavior to ensure consistent output.
Standard Requirements
The C standard does not explicitly require a specific result when printing boolean values. The behavior is implementation-defined and depends on the specific stream.
Boolalpha Flag
The standard streams (cout, cerr, etc.) have a boolalpha flag that controls the representation of boolean values. When set to false (default), boolean values are displayed as 0 (false) or 1 (true). When set to true, they are displayed as the strings "false" and "true."
Example:
The following code demonstrates the use of the boolalpha flag:
<code class="cpp">#include <iostream> #include <iomanip> int main() { std::cout << false << "\n"; std::cout << std::boolalpha; std::cout << false << "\n"; return 0; }</code>
Output:
Without boolalpha set, the output will be:
<code class="txt">0 false</code>
With boolalpha set, the output will be:
<code class="txt">0 false</code>
Localization
When boolalpha is set, the displayed strings for false and true can be localized based on the current locale. For example, the following code sets the locale to French and prints a boolean:
<code class="cpp">#include <iostream> #include <iomanip> #include <locale> int main() { std::cout.imbue(std::locale("fr")); std::cout << std::boolalpha; std::cout << false << "\n"; return 0; }</code>
Output:
<code class="txt">faux</code>
Customizing Boolean Representation
If necessary, it's possible to customize the representation of boolean values by creating a custom numpunct facet. The numpunct facet allows control over numeric formatting, including the true and false strings.
The above is the detailed content of How are Boolean Values Printed in C ?. For more information, please follow other related articles on the PHP Chinese website!