D Mehta
D Mehta

Reputation: 453

Why is an empty string literal treated as true?

Why is the condition in this code true?

int main ( )
{

   if ("")
      cout << "hello"; // executes!

   return 0;
}

Upvotes: 33

Views: 10791

Answers (3)

user3799364
user3799364

Reputation: 9

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.

Upvotes: 0

dlf
dlf

Reputation: 9393

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.

Upvotes: 38

TNA
TNA

Reputation: 2745

Because "" decays to a char const* and all non-null pointers evaluate to true if or when converted to a boolean.

Upvotes: 6

Related Questions