1

I am wondering why the following program compiles fine

#include <iostream> int main() { char a = false; if (!a) { std::cout << "kdjk"; } char b = true; if (!b) { std::cout << "ppp\n"; } return 0; } 

Output : prints kdjk

Why does assignment of bool value to char compiles without warnings?

3
  • 2
    It's implicit type conversion. true is 1 equals to SOH. false is 0 equals to NUL. Commented Aug 3, 2020 at 5:51
  • 1
    related: stackoverflow.com/questions/4276207/… Commented Aug 3, 2020 at 6:12
  • The why is in part that C++ had been developed with backwards compatibility to C, and in part when the bool type was actually added to the language it also used the fairly flexible implicit type conversions prevalent for other types. This is not a behavior that I like, but it would be a major breaking change to change the rules now, and would break C++'s rather impressive effort to maintain backwards compatibility to earlier C++ standards and C. Commented Aug 3, 2020 at 11:20

2 Answers 2

3

This:

char a = false; 

invokes an implicit conversion from bool to char. The language rules for converting a bool value to an integral type (such as char) say that:

A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one. The result is that the value of a is 0 and the value of b is 1.

Sign up to request clarification or add additional context in comments.

Comments

1

The value of false is 0 and that fits into character and ! is an operator that checks if the operand is 0 or not. That's why it works.

2 Comments

false is not a character.
@KeithThompson Updated the answer, it's 0 and it fits into the character.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.