+ 1
What will happen if we assign a float value to bool?
6 Respuestas
+ 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
+ 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. :-)
0
thanx man
0
u r welcome bro
0
output =1 /
true=1
0
because boolean is true or false