c++中空字符串解释为True的困惑

首先我们看这样这个问题

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就有的特性了。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值