Why is the condition in this code true
?
int main ( )
{
if (\"\")
cout << \"hello\"; // executes!
return 0;
}
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.
You are probably coming from a languange like PHP, where the check is processed different:
php -r 'echo "X";if ("") echo "Y";'
THis will print the X, but not the Y because the empty string has no value.
As others have pointed out, in C++ it's a non-null-pointer, so evaluated as true.
Because ""
decays to a char const*
and all non-null pointers evaluate to true
if or when converted to a boolean.