Why is an empty string literal treated as true?

后端 未结 3 782
长发绾君心
长发绾君心 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:32

    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.

提交回复
热议问题