首先我们看这样这个问题
int main ( )
{
if ("")
cout << "hello"; // executes!
return 0;
}
这对于其他非c++的程序员来说是很困惑的。为什么空的字符串是True?
这个问题其实归根到底是NULL与空字符串的区别。
空字符串实际上是const char[1]
,里面包含了\0
字符,这不是NULL,自然是True。
那么c++中到底什么表示True,什么表示False呢?
- 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.
上面摘自c++11草案中的描述。也就是0,空指针或空成员指针都为false,除此以外都是true。显然空字符串都不是上面的三者之一。
回顾上面程序的代码,其实这个代码的写法也是不好的,因为字符串不是一个布尔类型,把它当作布尔类型去使用,这本身就是不好的。比较好的做法是
#include <string>
std::string str = "";
if(!str.empty()){}
而且这是c++98就有的特性了。