c++中空字符串解释为True的困惑
发布日期:2021-06-29 16:00:21 浏览次数:2 分类:技术文章

本文共 790 字,大约阅读时间需要 2 分钟。

首先我们看这样这个问题

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 
std::string str = "";if(!str.empty()){}

而且这是c++98就有的特性了。

转载地址:https://coordinate.blog.csdn.net/article/details/79392193 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Python Pickle任意代码执行漏洞
下一篇:Python实现2048

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月21日 08时06分51秒