Why is the condition in this code true
?
int main ( ) { if ("") cout << "hello"; // executes! return 0; }
Yes. All false , 0 , empty strings '' and "" , NaN , undefined , and null are always evaluated as false ; everything else is true .
Truthy or Falsy When javascript is expecting a boolean and it's given something else, it decides whether the something else is “truthy” or “falsy”. An empty string ( '' ), the number 0 , null , NaN , a boolean false , and undefined variables are all “falsy”. Everything else is “truthy”.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null . It can be described as the absence of a string instance.
An empty string is not a valid json, then it fails.
A condition is considered "true" if it evaluates to anything other than 0*. ""
is a const char array containing a single \0
character. To evaluate this as a condition, the compiler "decays" the array to const char*
. Since the const char[1]
is not located at address 0, the pointer is nonzero and the condition is satisfied.
* More precisely, if it evaluates to true
after being implicitly converted to bool
. For simple types this amounts to the same thing as nonzero, but for class types you have to consider whether operator bool()
is defined and what it does.
§ 4.12 from the C++ 11 draft spec:
4.12 Boolean conversions [conv.bool]
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With