Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

c++ - What happens when you logical not a float?

I assume this just returns an int. Is there anything else going on I should be aware of? C/C++ differences?

float a = 2.5;
!a; // What does this return? Int? Float?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Regarding C++, quoting C++11 §5.3.1/9:

The operand of the logical negation operator ! is contextually converted to bool; its value is true if the converted operand is false and false otherwise. The type of the result is bool.

So what's really relevant here is the behavior of static_cast<bool>(some_float) – quoting §4.12/1:

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.

Putting those together, 2.5f is a non-zero value and will consequently evaluate to true, which when negated will evaluate to false. I.e., !a == false.


Regarding C, quoting 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. The result has type int. The expression !E is equivalent to (0==E).

I.e. the net result is the same as with C++, excepting the type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...