为什么空字符串文字被视为true? [英] Why is an empty string literal treated as true?

查看:621
本文介绍了为什么空字符串文字被视为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码中的条件为真

Why is the condition in this code true?

int main ( )
{

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

   return 0;
}


推荐答案

条件被视为真实如果评估为0 * 以外的任何其他内容。 是一个包含单个 \0 字符的const char数组。要将此值作为条件进行评估,编译器会将数组衰减为 const char * 。由于 const char [1] 不在地址0,因此指针非零并且条件满足。

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.

* 更准确地说,如果在隐式转换为<$ c后计算结果为 true $ C> BOOL 。对于简单类型,这与非零相同,但对于类类型,您必须考虑是否定义运算符bool()以及它的作用。

* 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:


4.12布尔转换[conv.bool]

4.12 Boolean conversions [conv.bool]

算术,无范围枚举,指针或指向成员类型的指针的prvalue可以是
转换为bool类型的prvalue。零值,空指针值,
或null成员指针值被转换为false;任何其他值是
转换为true。 std :: nullptr_t类型的prvalue可以转换为
到bool类型的prvalue;结果值为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.

这篇关于为什么空字符串文字被视为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆