+ 1

What will happen if we assign a float value to bool?

15th Jun 2016, 11:00 AM
Awais Ahmad
Awais Ahmad - avatar
6 Réponses
+ 2
it is perfectly ok and here is the reason: bool is either true or false. So when u assign it anything other than 0, then it becomes true. Here is the code for authentication: int main() { bool a = 1.23; cout << a; return 0; } try it out and see that it displays 1 which is true
15th Jun 2016, 11:29 AM
Sardor
Sardor - avatar
+ 2
I have to disagree to "it's perfectly ok". It compiles, and behaves as Sardor says, sure, but this is considered bad style. Bad style means this is considered bad practice as it *implicitly* (i.e. without stating it) converts the 1.23 to a bool. Not stating what you want to accomplish with the code impairs the readability of the code. Explicitly doing things will help yourself and others to read your code later on. Therefore in this case use bool b = static_cast<bool>(1.23); It does the same but directly states what you wish to accomplish. Also, with a higher level of warnings enabled in your project, the compiler should give you a warning about that implicit conversion. :-)
15th Jun 2016, 6:01 PM
Stefan
Stefan - avatar
0
thanx man
15th Jun 2016, 12:51 PM
Awais Ahmad
Awais Ahmad - avatar
0
u r welcome bro
15th Jun 2016, 12:53 PM
Sardor
Sardor - avatar
0
output =1 / true=1
18th Jun 2016, 2:37 PM
raees
0
because boolean is true or false
18th Jun 2016, 2:38 PM
raees