[英]What happens when you logical not a float?
I assume this just returns an int. 我假设这只返回一个int。 Is there anything else going on I should be aware of? 还有什么事情我应该知道吗? C/C++ differences? C / C ++的差异?
float a = 2.5;
!a; // What does this return? Int? Float?
Regarding C++, quoting C++11 §5.3.1/9: 关于C ++,引用C ++11§5.3.1/ 9:
The operand of the logical negation operator
!
逻辑否定运算符的操作数!
is contextually converted tobool
; 在上下文中转换为bool
; its value istrue
if the converted operand isfalse
andfalse
otherwise. 它的值是true
,如果转换后的操作数是false
和false
,否则。 The type of the result isbool
. 结果的类型是bool
。
So what's really relevant here is the behavior of static_cast<bool>(some_float)
– quoting §4.12/1: 所以这里真正重要的是static_cast<bool>(some_float)
的行为 - 引用§4.12/ 1:
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type
bool
. 算术,无范围枚举,指针或指向成员类型的指针的prvalue可以转换为bool
类型的prvalue。 A zero value, null pointer value, or null member pointer value is converted tofalse
; 零值,空指针值或空成员指针值转换为false
; any other value is converted totrue
. 任何其他值都转换为true
。 A prvalue of typestd::nullptr_t
can be converted to a prvalue of typebool
; 类型为std::nullptr_t
的prvalue可以转换为bool
类型的prvalue; the resulting value isfalse
. 结果值为false
。
Putting those together, 2.5f
is a non-zero value and will consequently evaluate to true
, which when negated will evaluate to false
. 将这些放在一起, 2.5f
是一个非零值,因此将评估为true
,否则将评估为false
。 Ie, !a
== false
. 即, !a
== false
。
Regarding C, quoting C99 §6.5.3.3/5: 关于C,引用C99§6.5.3.3/ 5:
The result of the logical negation operator
!
逻辑否定运算符的结果!
is0
if the value of its operand compares unequal to0
,1
if the value of its operand compares equal to0
. 是0
,如果它的操作数的值不相等的比较,以0
,1
,如果其操作数的值进行比较等于0
。 The result has typeint
. 结果是int
类型。 The expression!E
is equivalent to(0==E)
. 表达式!E
等价于(0==E)
。
Ie the net result is the same as with C++, excepting the type. 即净结果与C ++相同,除了类型。
See for yourself: 你自己看:
#include <iostream>
int main()
{
float a = 2.5;
if ( !a )
std::cout << !a << "\n";
else
std::cout << !a << "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.