Why is an empty string literal treated as true?

后端 未结 3 792
长发绾君心
长发绾君心 2021-01-07 17:19

Why is the condition in this code true?

int main ( )
{

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

   return 0;
}
         


        
3条回答
  •  情歌与酒
    2021-01-07 17:26

    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.

提交回复
热议问题