简体   繁体   English

如果你不是浮动的话,会发生什么?

[英]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 to bool ; 在上下文中转换为bool ; its value is true if the converted operand is false and false otherwise. 它的值是true ,如果转换后的操作数是falsefalse ,否则。 The type of the result is bool . 结果的类型是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 to false ; 零值,空指针值或空成员指针值转换为false ; any other value is converted to true . 任何其他值都转换为true A prvalue of type std::nullptr_t can be converted to a prvalue of type bool ; 类型为std::nullptr_t的prvalue可以转换为bool类型的prvalue; the resulting value is false . 结果值为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 ! 逻辑否定运算符的结果! is 0 if the value of its operand compares unequal to 0 , 1 if the value of its operand compares equal to 0 . 0 ,如果它的操作数的值不相等的比较,以01 ,如果其操作数的值进行比较等于0 The result has type int . 结果是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 ++相同,除了类型。

From here 这里开始

A float will be converted to false if its exactly 0.0f, 如果float正好为0.0f,则float将转换为false,
It will be also true if its not exacly 0.0f! 如果它不是真的0.0f也是如此!
Inifinity will also be converted to true. Inifinity也将转换为true。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM